These loops are driving me crazy!


#1

https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661#

When I try to run the code I receive an error:
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.

Any and all help is appreciated!!


var myName = "Anthony";
var hits = [];

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


#2

your second for loop is
for(var j = i; j < myName.length; i++)
should it be?
suppose myName.length=6
how many words do you want to print?
think :bulb:

@tacodestroyer


#3

We need to include the offset i in this expression:

j < i + myName.length;

so that the iteration takes place in the correct part of the text. Say a match is found at index 8. Without the offset, the inner loop will not run. With the offset, the inner loop will run from position 8 through 16 (but only push index 8 through 15).


#4

Well, I just fixed it for the

j < i + myName.length;

and now it keeps crashing. meh.


#5

Be sure to increment j in the inner loop. Your code is incrementing i.


#6

Just corrected that and...

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

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.

I'm definitely re-doing this after I figure out is wrong


#7

if (text[j] === 'A')//wrong

@tacodestroyer


#8

Got it fixed! w00t!

Thanks all!