Reputation: 1033
I am trying to create an array for listing purposes in Ionic Framework and check all the callcenter name's first char to add them in an alphabet array.
for (var i = 0; i < callcenterList.length; i++) {
var value = callcenterList[i]._owner && callcenterList[i]._owner.company.name[0];
if ((alphabet.indexOf(value) == -1 && isNaN(parseInt(value))) ||
(isNaN(alphabet[0]) && !isNaN(value))) {
if(!isNaN(value))
value = 123;
alphabet.push(value);
callcenterList.splice(i, 0, {
divider: {
alphabet: value
}
});
}
};
Replacing value = 123
with value = '#'
causes Google Chrome and Google Chrome Canary to malfunction and immediately use up to 100% of RAM in Mac.
Is this a Javascript bug or is it related to Google Chrome itself?
Upvotes: 5
Views: 170
Reputation: 12806
Since it is hard to believe that length is being re-evaluated, here is a simple example of what problems you might get
Without the break statement, the code will run in an endless loop. (Check the console log for how long the list might be)
var list = [0,1,2,3];
for (var i = 0; i < list.length; i++) {
list.push(i);
if (i > 1000) {
break;
}
}
console.log( list.length );
Your code does exactly the same, except that your splice function will add the new element at the specific position of your list (nl, your index). In the end, it will still increase the length, and your list will be one longer
Upvotes: 1
Reputation: 156624
This isn't a bug in your browser or anything: you're just creating a condition where your code goes into an infinite loop, which always tends to make the browser seize up. You can do the same thing with a simple while (true) {}
loop.
Specifically, you are iterating over the callcenterList
, and any time isNaN(alphabet[0])
, you are splicing a new element into callcenterList
. alphabet[0]
is going to have the first value that you push there which, in the conditional you're looking at, you're going to set to '#'
.
Therefore, isNaN(alphabet[0])
will always be true.
Therefore, you'll continue to add values into callcenterList
.
Therefore i < callcenterList.length
will always be true.
Upvotes: 6