5. second for loop


#1


Replace this line with your code.


#2

Your code isn't visible. To make it visible wrap it in backticks like so:

```
code goes here
```

#3

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

The part I don't understand is why the second "for" loop ends with: j < i + myName.length. I'm hoping someone can point out my error in logic.

I know that myName.length = 5. I also know that an array would identify all five characters as [K=0, E=1, V=2, I=3, N=4].

The hint on the exercise indicates that "Your loop should stop when it hits the value of the first iterator (say, i) plus the length of your myName variable."

The value of the first iterator in my case is K. Also, as stated above, myName.length = 5. To me, this seems to mean the iteration would stop after K plus 5 character positions, which of course is longer than my name.

So here is my question - Why does the loop end with i + myName.length, instead of just myName.length? My thinking is that j < myName.length would iterate a total of five character spaces, or [0, 1, 2, 3, 4], which is my entire name. What is the purpose of adding i here to myName.length?

Thanks for your help and any insight you can provide.


#4

Sorry it's 3:56 AM where I am, I'll try my best to answer later :stuck_out_tongue:


#5

If your myName.length is 5 and you set your for loop condition to j<myName.length, that loop would run 4 times. Then hits.push(text[j]) only collects [K,E,V,I] into the hits array.

In your 2nd loop, i represents K which holds position 0 in the hits array. So by adding i to myName.length, you are enabling the loop to run 5 times. This collects positions 0,1,2,3,4 into the hits array or [K,E,V,I,N].


#6

Thanks very much!! This is the first explanation I've read that's made sense to me. I've been thinking about this exercise for far too long. Thanks again!


#7

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