Charlie Sheather
Charlie Sheather

Reputation: 2374

Javascript - for loop hanging?

Maybe I've just been staring at this screen for too long, but I cannot seem to work out why this for loop is hanging?

var not = '3,7';
var nots = not.split(',');
alert(nots.length);
for (var i = 0; i <= nots.length; i++) { 
    nots[i] = parseInt(nots[i], 10);
}
document.write(nots);

Thanks for any help.

Cheers
Charlie

Upvotes: 0

Views: 440

Answers (1)

cdhowie
cdhowie

Reputation: 168998

In the loop you are testing if i <= nots.length. You should be testing if i < nots.length.

When the length is 5, there will elements at indexes 0, 1, 2, 3, 4. So when i reaches 5, there are no more elements. But then you set nots[i] (element 5) and extend the array by one. So each time the loop executes when i is equal to nots.length, you are extending the array by one, and so the loop runs "just one more time" only to extend the array further.

Upvotes: 5

Related Questions