Your Second For Loop & .push()


#1

Hello, I am hoping to get some help with this exercise:
Your Second "For" Loop


From what I understand the first for loop will count the text starting from position 0, and the if statement will look for "L". I am stuck at the second for loop. When I make another for loop, j , why does it need to be set equal to i? Also why am I putting j < (myName.length + i) and not just j <(myName.length). Why add the +i? I am also not understanding how .push() works based on the explanation in the exercise. Another question that comes to mind, how does the computer know that myName is being used based only on the first letter? What if I had another word in the string 7 letters long that starts with L? Hope these questions aren't too weird. Any help is appreciated. Thank you.

Here is the code:

var text = ("I am putting my name, Lindsey, in this string. Then I will count how many times my name has been used in this string.")

var myName = ("Lindsey")

var hits = [];

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

       hits.push(text[j]);
    }
}


Replace this line with your code.


#2

Say we have some text...

"this is some text, Lindsey, wherein we search for the first letter"

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

}

L will be found at i = 19. We will next iterate over text from that position, so

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

    }

In the above, i is the offset. myName.length is 7, so we will be pushing the letters from index position 19 through 25. See where the i + myName.length comes in?


#3

Thank you! I see why the second loop is equal to i. Does i+ myName.length tell the push method where to start and end?


#4

Not really telling the push method anything, just the loop. All hits.push() does is append the array. The inner loop is controlled by j and j < i + myName.length. Tantamount to writing,

for (var j =  19; j < 26; j++) {

}

Of course we would not actually write it this way since it would not be dynamic. By using the variables we can find multiple instances of "L" in the text, and iterate over each instance we find.


#5

Thankyou man... :slight_smile:


#6

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