为什么在 JavaScript 中使用数组的“for(var item in list)"被认为是不好的做法? [英] Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?

查看:111
本文介绍了为什么在 JavaScript 中使用数组的“for(var item in list)"被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个简单的基于零的数字索引数组:

Given a simple zero based, numerically indexed array:

var list = ['Foo', 'Bar', 'Baz'];

很多时候,我注意到当有人建议像这样循环遍历数组中的变量时:

Many times, I have noticed that when someone suggests looping through variables in an array like this:

for(var item in list) { ... }

...几乎可以肯定有人认为这是不好的做法并提出了替代方法:

...there's almost certainly someone suggesting that that's bad practice and suggests an alternative approach:

var count = list.length;

for(var i = 0; i < count; i++) {
    var item = list[i];
    ...
}

不使用上面更简单的版本而是使用第二个示例的原因是什么?

What's the reasoning for not using the simpler version above and to use the second example instead?

推荐答案

首先,for...in 循环的循环顺序是未定义的,因此不能保证属性将是按照您想要的顺序进行迭代.

First, the order of the loop is undefined for a for...in loop, so there's no guarantee the properties will be iterated in the order you want.

其次,for...in 迭代对象的所有可枚举属性,包括从其原型继承的属性.对于数组,如果您的代码或页面中包含的任何库增加了 Array 的原型,这可能会影响您,这可能是一件真正有用的事情:

Second, for...in iterates over all enumerable properties of an object, including those inherited from its prototype. In the case of arrays, this could affect you if your code or any library included in your page has augmented the prototype of Array, which can be a genuinely useful thing to do:

Array.prototype.remove = function(val) {
    // Irrelevant implementation details
};

var a = ["a", "b", "c"];

for (var i in a) {
    console.log(i);
}

// Logs 0, 1, 2, "remove" (though not necessarily in that order)

这篇关于为什么在 JavaScript 中使用数组的“for(var item in list)"被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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