Problem with second for loop


#1
var text = "Blah blah blah blah blah blah John \
blah blah blah John blah blah John blah blah \
blah blah blah blah blah John";
var myName = 'John';
var hits = [];
for (var i =0; i < text.length; i++){
    if (text[i] === 'J'){
        for(var j = i; j < (myName.length); j++ ){
            hits.push([j]);
        }
            
        }
    
    }

It keeps saying areful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.

I just don't understand what's going on here?


#2

Hi in your second for loops (myName.length) should be like that (myName.length + i )


#3

This is very close, unfortunately the logic is just a bit off, if you look at the condition you'll understand that as soon as you set "j" to "i" j will be greater than (myName.length). Essentially it will never run the "hits.push([j]);" line.

So when it says "Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length." it means add "i" to that condition to make it start at the beginning of the "John" string. It will keep iterating and adding the next letter of your name "John" to the "hits" array.

So try doing this!

for(var j = i; j < (myName.length + i); j++ ){

The logic behind this is kind of complex so I understand why you're having trouble. But essentially "i" will iterate itself until it finds the string "J" which is the beginning of your "myName" variable. After that, "j" will then iterate until it gets to the end of your "myName" variables length.

I hope this helps!
:+1:


#4

Yeah it helped a lot. Thanks.