开发者

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(no开发者_开发技巧ts);

Thanks for any help.

Cheers

Charlie


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜