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

查看:98
本文介绍了为什么使用数组'的(VAR在列表项)'认为不好的做法在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

首先,循环的顺序是未定义的为中... 循环,所以有不保证该属性将你想要的顺序进行迭代。

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.

二,为...超过一个对象,包括那些从它的原型继承了所有枚举的属性迭代。在数组的情况下,这可能会影响你,如果你的code或包含在你页面的库增强阵列的原型,它可以是一个真正有用的东西要做到:

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)

这篇关于为什么使用数组'的(VAR在列表项)'认为不好的做法在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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