Second "for" loop


#1



5. Your second for loop

I'm able to pass this exercise with my code, but I just don't understand what the second for loop is doing. Could someone please help me understand?


Replace this line with your code. 
var text = "steve text";
var myName = "steve";
var hits = [];

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


#2

why not simply add a console, log so you can see what is happening?

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

agree with me that i will hold the index of the first letter of your name the moment the second for loop start running? (thanks to your if condition: if (text[i] === myName[0]) )

to start the second loop, you give j the value of i: j = i, now j has the first letter of your name as well. Now you are going to loop over it. and i + myName.length is the end of your name, so now your name is pushed into an array, letter by letter


#3

Unfortunately the correction algorithm of the tutorial does not support the following arrangement for which is correct as well:

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


#4

that will indeed also work, but there are thousand and one way to solve this problem (well, in figure of speech), unfortunately we can't allow them all)


#5

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