5. Your Second for Loop


#1


After few hours, I finally landed on a code that runs, but frankly have no idea why and would love someone to break down the meaning behind said code.

What I don't mainly understand is 1) why is the second var set to j, and why is it equal to i?
2) Wouldn't we have to assign each character in the name different alphabets (eg k, l, m, n) for the loop to run?

Sorry if I sound thick headed but for some reason I can't grasp myhead around this bit, and would love some insight. Thanks



Replace this line with your code.


#2

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

        }
    }
}

Let's say we have some text,

text = "This is a long string that contains Fish somewhere in the text."

The outer loop is iterating over the text starting at index 0 and moving to the right. F is found at i === 36.

We set j to 36 and then iterate from that point over the four letters of the name, Fish.

i === 36
j === 36, 37, 38, 39, 40

i + 4 === 40 so that will be where the loop terminates (j < i + myName.length), pushing only the above four indexed letters (text[j]) to the hits array.


#3

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