简体   繁体   English

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

[英]Javascript: Why use a for loop instead of a for-in loop for arrays?

I have been reading Object-Oriented Javascript by Stoyan Stefanov, and at one point he writes:我一直在阅读 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). for-in循环用于遍历数组元素(或 object,我们将在后面看到)。 This is it's only use;这是它的唯一用途; it can not be used as a general-purpose repetition mechanism that replaces for or while .它不能用作替换forwhile的通用重复机制。 Let's see an example of using a for-in to loop through the elements of an array.让我们看一个使用for-in循环遍历数组元素的示例。 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-in主要适用于对象,而常规for循环应该用于数组。

I have always used for loops in the past when iterating of the elements of an array and I have usually seen for loops not for-in loops used for this purpose, but what is the reason that the "regular for loop should be used for arrays"?我过去在迭代数组元素时一直使用for循环,我通常看到for循环不是用于此目的for-in循环,但是“常规for循环应该用于数组”的原因是什么“?

The reason to use regular for loops for arrays is that it limits the iteration to indexed values.对 arrays 使用常规for循环的原因是它将迭代限制为索引值。

If you use a for-in loop, it will iterate through all properties on the object (an array is an object), and may give you unexpected results if you attach arbitrary properties to an array that aren't numerically indexed.如果您使用for-in循环,它将遍历 object 上的所有属性(数组是一个对象),并且如果您将任意属性附加到没有数字索引的数组,可能会给您带来意想不到的结果。

The issue is that some libraries (Prototype comes to mind) extend the array type, so when you use a for in loops, it hits all of the enumerable properties on that array, which includes all elements of the array, but also all added on properties or methods.问题是某些库(想到原型)扩展了数组类型,因此当您for in ,它会命中该数组上的所有enumerable属性,其中包括数组的所有元素,但也都添加到属性或方法。 Not what you want to have happen.不是你想要发生的事情。

The for i in loop iterates only over the elements of the array, that is, anything you'd define literally as [1, 2, 3, 4] . for i in循环仅迭代数组的元素,即您定义为[1, 2, 3, 4]的任何内容。

Well i mostly use it when i dont know the exact number of elements in an array.好吧,当我不知道数组中元素的确切数量时,我主要使用它。 in general it is used for iterating on elements when the array is dynamically or on the fly populated.通常,它用于在动态或动态填充数组时对元素进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM