Not pushing letters into hits array, help me!


#1

I cannot for the life of me figure out what i'm doing wrong here.

var text = "Jeff is rad also other stuff is going on i need / to finish this coding practice Jeff so that i can enjoy/ my last weekend with no work before school starts Jeff!"
var myName = "Jeff";
var hits = [];
for(var i = 0; i < text.length; i ++) {
if(text[i] === "J")
{
for(var j = i; j < (i + myName.length); j ++) {
hits.push(text["j"]);
}
}
};

`


#2

Same here.
I'm using the same code with an if else statement at the end, but the return I get is a whole bunch of "Undefined".
This is considered correct by this page.


#3

Youre variable is a string. You arent targetting any index of text with a string of "j".


#4

wow, thank you! i was staring at this for over an hour


#5

YW, and dont worry, youll have plenty more opportunities just like this one. :wink:


#6

But when I remove the "" I get a return "ReferenceError: M is not defined"

Or else if I enter the full name "Martijn" as variable I get;
[ ]
[ ]
[ ]
So it prints [ ] instead of the name.

At the end I have;

if (hits.length=0){
console.log("Your name wasn't found!");
}
else{
console.log(hits);
}
}
}


#7

Im going to need all of the code together to see whats wrong.


#8

This is it;

'''
/*jshint multistr:true */
var text = "Martijn mag er zijn, want Martijn is fijn, en het is fijn om bij Martijn te zijn!";

var myName = "Martijn";

var hits = [];

for (var i = 0; i < text.length; i++){
if (text[i] === "M"){
for (var j = i; j < (i+myName.length); j++){
hits.push(text["M"]);
}
if (hits.length=0){
console.log("Your name wasn't found!");
}
else{
console.log(hits);
}
}
}
'''


#9

Ok, i see. Its almost the same problem, you arent using the j variable though; but you removed the quotations. You are supposed to pass in the variable youre using for the for () loop. OP did that, but he made it a string.

In your case yourr passing in "M". So you need to remove all of it and use you loop iterator, j.


#10

ah yes, that did the trick.
Many thanks!


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.