Javascript - for循环挂起?

发布于 2024-12-01 18:52:57 字数 278 浏览 2 评论 0原文

也许我只是盯着这个屏幕太久了,但我似乎无法弄清楚为什么这个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

杯别 2024-12-08 18:52:58

在循环中,您正在测试是否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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文