Javascript:为什么使用for循环而不是数组的for-in循环? [英] Javascript: Why use a for loop instead of a for-in loop for arrays?

查看:121
本文介绍了Javascript:为什么使用for循环而不是数组的for-in循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been reading Object-Oriented Javascript by Stoyan Stefanov, and at one point he writes:


for-in 循环用于迭代数组元素(或对象,我们稍后会看到)。这是唯一的用途;它不能用作通用重复机制,在时替换或。让我们看一个使用 for-in 循环遍历数组元素的示例。但请记住,这仅供参考,因为 for-in 主要适用于对象,而常规适用于循环应该用于arrrays。

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-in 循环用于此目的,但是循环的常规应该用于数组的原因是什么?

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"?

推荐答案

问题是某些库(Prototype浮现在脑海中)扩展了数组类型,所以当你在循环中使用时,它命中该数组上的所有可枚举属性,其中包括数组的所有元素,但也包含属性或方法上的所有元素。不是你想要发生的事情。

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. Not what you want to have happen.

循环中的i的只迭代数组的元素,也就是说,你在字面上定义为 [1,2,3,4]

这篇关于Javascript:为什么使用for循环而不是数组的for-in循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆