Your second for loop stuck


#1

/*jshint multistr:true */

var text = "I went to the store today with myself, jake"
var myName = "jake"
var hits = []
for ( var i = 0; i <= text.length; i++){
if (text[i] === myName[0]){
for( var j = i; j <= myName.length; j++){
hits.push(text[j]);
}
}
}
console.log(hits);

--- i really dont understand why this wont run i keep changing it around every which way and it continues to just say Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.


#2

@z0rzzz,

Maybe a diagram demonstrates it....

https://discuss.codecademy.com/t/the-second-for-loop-for-searching-your-name-in-text/29423/2?u=leonhard.wettengmx.n


#3

Now I've changed my code to that and it's still giving me an error message. Idk if it's bugged or what. I am also wonder if I could just put j <= myName.length as it still allows for the full 4 letters whereas j< I +myName.length is still just less than 5 which is the same as 4.


#4

@z0rzzz,

Maybe if you look at it in this way...

As programming is the attempt
to copy the reality....

You have a piece of text,
with your left-finger you scan this text
character for character, and keeping count with i

At every character you check

  • is this character the same as the firstCharacterOf_myName
    ( thus myName[0] )

  • If so....
    start reading with your right-finger at this position i
    but for the right-finger we use counter j
    so we start counting at j = i
    we will [repeat] the following action
    as long as we have incremented less than myName.length
    thus j < ( i + myName.length)

The action:
write the character of the right-finger in an Array
hits.push(text[j]);
goto [repeat]

so the second for-loop looks like
for (var j = i ; j < ( i + myName.length ) ; j++ ) {
hits.push( text[j] );
}


Your second "for" loop
Doubt in second for loop 5
#5

I also get an error message for this exact code. I'll just assume it's correct and move on with my life!