gpt4 book ai didi

Javascript:为什么对数组使用 for 循环而不是 for-in 循环?

转载 作者:行者123 更新时间:2023-11-29 10:23:34 25 4
gpt4 key购买 nike

我一直在阅读 Stoyan Stefanov 的《面向对象的 Javascript》,有一次他写道:

The for-in loop is used to iterate over the element of an array (or an object, as we'll see later). This is it's only use; it can not be used as a general-purpose repetition mechanism that replaces for or while. Let's see an example of using a for-in to loop through the elements of an array. But bear in mind that this is for informational purposes only, as for-in is mostly suitable for objects, and the regular for loop should be used for arrrays.

我过去在迭代数组元素时一直使用 for 循环,我通常看到的是 for 循环而不是 for-in 循环用于此目的,但是“常规 for 循环应该用于数组”的原因是什么?

最佳答案

对数组使用常规 for 循环的原因是它将迭代限制为索引值。

如果您使用 for-in 循环,它将遍历对象的所有属性(数组是对象),如果您将任意属性附加到数组,可能会给您带来意想不到的结果没有数字索引。

关于Javascript:为什么对数组使用 for 循环而不是 for-in 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6637240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com