Help with Your second "for" loop!


#1

I'm having a little trouble understanding the hits.push() method.

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

Can someone explain it in a little more detail and where to place it? Thank you!


#2

We won't be needing that. However, the for statement will be needing a code body.

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

#3

Let me try and break it down for you.

my name is Chris in my code.

Remember in a string of text the loop counts. It counts each character starting at 1, 2, 3...

First loop says look through all of the characters and IF you find C, stop and run the next code block.

At this point it found the start of my name but needs instructions to push all of the characters and ONLY the characters in my name to the array. Remember it's not looking for h, r, i, s. It's only looking at the count in the text string.

In my example, C was the 6th count in my text string.

We found C. Now let's check to see how many characters are in the name Chris. It's 5.

So now we found the first C which is the 6th character. We know my name is 5 characters long. So now we want to push 5 characters to the array starting at the 6th string count. We want to push character counts 6 (C), 7 (h), 8 (r), 9 (i), 10 (s). But how we do we tell the loop to stop pushing characters to the array. It doesn't know that your name ends with an s.

for (var j = i; j < (myName.length + i); j++) Could read as we know that i is 6 because it stopped on the 6 character which is C. We want to start our second loop off on the C character or 6th spot. So we set j as i.

(var j = 6; 6 < (5 + 6); 6++) =
( 6; 6 < 11); 6 ++)
Our setup starts at 6 or C;
Our condition is we know Chris is 5 characters. We are starting at 6th spot. We want to find 5 characters. 6 + 5 = 11. We want to stop after we have found all 5 characters of Chris. That's how we know we have the name.
Then add one to 6 and so on in each loop until it reaches 11 and stop.
On each loop it's going to push that number of the text string to the array.

The numbers will be different depending on where your name falls in the text string count.


#4

5 posts were split to a new topic: There is an unexpected token


#10

@archbowdestroyer, could you please start a new topic for your own question? I keep getting notifications for answers to your problem.

Thanks @mtf!


#11

4 posts were split to a new topic: your second 'for' loop isn't pushing values to the hits array


#15

excellent explanation, this really helped me relate to the code, thanks!