Your second "for" loop - infinite loop


#1

/*jshint multistr:true */
var text = "Hi, my name is Jeremy Tan hi hi helloworld.";
var myName = "Jeremy";
var hits = [];
for (var i = 0; i < text.length; i++) {
    if (text[i] === myName[0]){
        for (var j = i; j < i + myName.length; j++){
            hits.push(text[i+j]);
        }
    }
}

This is my current program, and it works. However, if in either for loop, I change the < to =, the program will crash my browser.
Can someone please explain this to me? I really don't understand why it becomes an infinite loop.


#2

What? If you change:

for (var j = i; j < i + myName.length; j++)

to:

 for (var j = i; j = i + myName.length; j++)

Because a single equal sign you assign a value, even if (you don't) want to do this, at least use two equal signs to compare


#3

/*jshint multistr:true */

var text = "Lalalal lalalllal lalallalalal Fabio \
lalala Fabio lalalalla Fabio \
lalllalalla lalalalal Fabio";

var myName = "Fabio";
var hits = [];

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


#4

Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable.


#5

this line:

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

See something wrong? I see a semi-colon which shouldn't be there


#6

that was the issue....thanks a lot


#7

When I use this code, the program works:
for (var i = 0; i < (text.length); i++) {
for (var j = i; j < (i + myName.length); j++){

However, if I change either of the "<" to "=", the web browser crashes:
for (var i = 0; i = (text.length); i++) {
for (var j = i; j = (i + myName.length); j++){

I don't understand why this change causes the browser to crash. Can someone explain the logic to me?

Also, I think that the second 'for' loop is not pushing values to the array yet, but I'm still trying to figure this out myself.


#8

well, now here:

 j = (i + myName.length)

you assign j a value of i + myName.length, at least use two equal signs to compare, then it wouldn't crash, but it will print an additional character at the end of your name