6/7 The second loop is driving me nuts


#1




This is where I am.


So I passed this exercise but honestly I don't understand most of it.
No matter how many times I read that second for loop, I can not seem to understand it.

Also, whenever I run my code I get undefined values logged to the console :
[ undefined, undefined, undefined, undefined, undefined ]


/*jshint multistr:true */

text = "a b c d Billy is a boy e f g h etc.";
var myName = "Billy";
var hits = []

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

if(hits.length === 0)
{
    console.log("Your name wasn't found!");   
}
else
{
    console.log(hits);   
}


Search text question
#2

Hello @billy5500,

in your second for loop, you have to hits.push() the jth character of text not myName. That will fix your "undefined" problem.


#3

And as for the function of the code...

What the first for loop does is it iterates over the length of the text variable. Then, in the if loop, you check if one of the characters in the text variable is the first letter of your own name. What the second for loop does is it pushes the text starting from the point where it found the first letter of your name to the length of your name characters to hits.

Hope this clears out your doubts...


#4

I think I've got it now. The undefined output made it confusing but it makes sense now.
Thank you!


#5

No worries, @billy5500, keep coding hard :laughing:!


#6

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