ActionON
ActionON

Reputation: 106

Infinite loop for unknown reasons

I am confused as to why this:

regResponse.splice(i+1, 0, newString);

causes an infinite loop or something of the sort (page doesn't load). If I put it outside the if block, it isn't an infinite loop but then the logic of what I'm trying to do won't work. How is this happening? I can't see why it freezes the page.

If you put

break;

directly after the regResponse.splice line, you'll see within console log the logic of what I'm doing is starting to come together as the title and the link itself are now separated for the first three items (until it reaches the if loop condition and breaks out of it).

var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddessAh! My Goddess TV|http://www.anime-planet.com/anime/ah-my-goddess-tvAi Yori Aoshi|http://www.anime-planet.com/anime/ai-yori-aoshiAir Gear|http://www.anime-planet.com/anime/air-gear"

myString = myString.replace(/([a-z])([A-Z])/g, '$1 $2');

var reg = /[^|]+/g;
var regResponse = myString.match(reg);
console.log(regResponse);


for(i = 0; i < regResponse.length; i++) {
    if (regResponse[i].length > 20) {
       space = regResponse[i].indexOf(' ');
        var newString = regResponse[i].substring(space+1, regResponse[i].length);
        regResponse[i] = regResponse[i].slice(0, space);
        regResponse.splice(i+1, 0, newString);



    }

}

Upvotes: 0

Views: 93

Answers (2)

jperezov
jperezov

Reputation: 3171

Your terminating condition depends on regResponse.length, but you are also adding elements to regResponse.

Here is the documentation on Array.splice.

Let's dive into your code:

for(i = 0; i < regResponse.length; i++) {
    if (regResponse[i].length > 20) {
       space = regResponse[i].indexOf(' ');
        var newString = regResponse[i].substring(space+1, regResponse[i].length);
        regResponse[i] = regResponse[i].slice(0, space);
        regResponse.splice(i+1, 0, newString);
    }
}

Let's see why this isn't terminating. We're going to assume where at a value of i in which the loop should end after, i.e. i === regResponse.length - 1. Now, the line regResponse.splice(i+1, 0, newString) will append a new element to the end of the regResponse array. Now i === regResponse.length - 2.

It looks like you had meant for if (regResponse[i].length > 20) to be your terminating statement. Try if (regResponse[i].length < 20) instead.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

The infinite loop is a result of extending the array (with splice) as you're looping through it. Try performing your loop backwards to avoid this:

for (i = regResponse.length-1; i>=0; i--) {

http://jsfiddle.net/mblase75/cgop02f1/

Upvotes: 2

Related Questions