Javascript - for循环挂起?
也许我只是盯着这个屏幕太久了,但我似乎无法弄清楚为什么这个 for 循环挂起?
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);
感谢您的任何帮助。
干杯
查理
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在循环中,您正在测试是否
i <= nots.length
。您应该测试是否i
i
i
i
i
i
i
i
i
nots.length
。当长度为5时,索引0、1、2、3、4处会有元素。所以当
i
达到5时,就不再有元素了。但随后您设置了 nots[i](元素 5)并将数组扩展一。因此,每次当i
等于nots.length
时执行循环,您都会将数组扩展一,因此循环“仅再运行一次”进一步扩展阵列。In the loop you are testing if
i <= nots.length
. You should be testing ifi < 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 setnots[i]
(element 5) and extend the array by one. So each time the loop executes wheni
is equal tonots.length
, you are extending the array by one, and so the loop runs "just one more time" only to extend the array further.