Searching text exercise: can't understand why loop is stuck


#1

Hello!

This code work:
/*jshint multistr:true */
var text = "Hello mate, how are you? Here is\
Abdul. Yes Abdul! That's me Abdul";

var myName = "Abdul"

var hits = []

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

But why this one isn't? It crushes the website

/*jshint multistr:true */
var text = "Hello mate, how are you? Here is\
Abdul. Yes Abdul! That's me Abdul";

var myName = "Abdul"

var hits = []

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

I would've think if I declare j = i in the second loop then adding either j or i to my myName.length is the same?

Can anyone explain?


#2

Close, but your logic is a little incorrect.

for (j = i; j hits.push(text[j]);

remember that for loops have 4 parts.

for( initialization ; condition ; postfix ) { /*Code*/ }

so let's initiate the "j" give it a condition, and it's increment property.

it would look like this.

for( var j = i ; //This is telling it where to start.
j < (name.Length + i) ; //This tells us our ending point
j++ ) //Postfix, this lets us know how fast we're incrementing or decrementing.
{ ... } //This is where the code would be after the fact.

Go ahead and put this together, if you have any questions on how that works just ask, I'll explain it more fully if you need it.


#3

Thanks Lolman for quick reply.
I guess my question really is why swapping i for j in the second condition of the for loop is causing infinite loop (i.e. crushing website)

for( var j = i ; 
j < (name.Length + j) ; //Here is j instead of i. Why is this a problem if we declared j=i which would be the same
j++ ) 
{ ... }

I realized in the previous question I haven't type the code correctly to make my question clear.