5. Your second "for" loop (Almost there, but what's wrong with my code?)


#1

I need help finding out why I get the error shown bellow this code. Thanks!

var text = "Clemente. Hey, what's up? My name is \
Clemente. Clemente.";

var myName = "Clemente";

var hits = [];
for (var i= 0; i if(text[i] === "C") {
for (var j = i; j < (myName.length + i); j++){
hits.push([j]);
}
}
}
console.log(hits);

Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable.


#2

Hi @blinkflash ,

You problem lies with your first for-loop.

the formula is:
for(var START; END; ACTION){
//do something
}
you've got an if-statement started in the middle.
If you finish your for-loop conditions, THEN move on to the if-statement.

Hope this helps!


#3

Not sure if your question has been answered, however the "if" statement has to be outside the "for loop"
for example, your code should look like this
here is my code,

var text= ("it is a sunny day for Christian, he chose, who? Christian of course, but he's not really a Christian,or is he?");
var myName = ("Christian");
var hits= [];

for (var i=0; i < text.length; i++){
if (text[i] === "C"){
for (j = i; j < myName.length+i; j++){
hits.push(text[j]);
}
}
}

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

else    {
    console.log(hits);
}

Your "if" statement has to be outside the "for loop"

// i


#4

I am getting the same error message as above.

"Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable."

Here is my code:

var text = ("Hello ! My name is Adam! This sure is hard stuff to learn, eh? Adam is my name, blah blah blah.");
var myName = "Adam";
var hits = [];

for (i = 0; i < text.length; i++){
if (text[i] === "A"){
for (j = i; j < (myName.length + i); j++)
newArray = [];
newArray.push(myName);
newArray[0];
}
}

Thanks for any guidance :smile:


#5

Hi Adam remove all instances of new array.

your second for loop should look like this

for(var j = i; j < i + myName.length; j++)
{
hits.push(text[j]);
}

you don't need the () in the comparison
the exercise wants you to add your name to the hits array so you don't need to create another array :slightly_smiling: