Your second "for" loop explanation


#1


So it seems that current code works fine. The problem is - I do not understand how the second loop works at all. Could somebody please explain to me in details step by step, how and why this second loop works.


/*jshint multistr:true */

var text="hey jack its fun";
var myName="jack";
var hits=[];

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


#2

you have the following string:

"hey jack its fun"

lets add the indexes:

h   e   y   _   j   a   c   k
0   1   2   3   4   5   6   7

i represented the space with a underscore.

so your name is at the following indexes:
4, 5, 6 and 7.

so then we start looping over the string, until we find the first letter of your name:

if (text[i]===myName[0])

this condition is true when i is 4

so then we want to retrieve your name from the string, so we need another loop. First we give a the value stored in i (i contains the index of the first letter), why you set a to 1, i don't know.

then we need a way to stop our second for loop, we do this by using i (which contains the first index) and myName.length (i (4) + myName.length (4))

This process would repeat if jack was a second time in your string, but with a different value for i (the first loop continues after the second loop has finished)


#3

Holy cow I got it! That a = 1 in the second loop was actually a huge mistake, but thanks to you I've finally understood how the second loop works. Here's the final version of code and again, huge thanks for the respond.

var text="hey jack its fun jack have jack some time jack";
var myName="jack";
var hits=[];

for (var i=0;i<text.length;i++){

if (text[i]===myName[0]){

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

}}}
console.log(hits)

#4

i felt my explanation was not that good, i wrote better explanations in the past:


But good you understand :slight_smile:


#5

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