First of all, never use a for in
loop to enumerate over an array.
(首先, 永远不要使用for in
循环来枚举数组。)
Never.(决不。)
Use good old for(var i = 0; i<arr.length; i++)
.(使用good old for(var i = 0; i<arr.length; i++)
。)
The reason behind this is the following: each object in JavaScript has a special field called prototype
.
(这背后的原因如下:JavaScript中的每个对象都有一个名为prototype
的特殊字段。)
Everything you add to that field is going to be accessible on every object of that type.(您添加到该字段的所有内容都将在该类型的每个对象上都可访问。)
Suppose you want all arrays to have a cool new function called filter_0
that will filter zeroes out.(假设您希望所有数组都有一个名为filter_0
的酷新函数,它将过滤掉零。)
Array.prototype.filter_0 = function() {
var res = [];
for (var i = 0; i < this.length; i++) {
if (this[i] != 0) {
res.push(this[i]);
}
}
return res;
};
console.log([0, 5, 0, 3, 0, 1, 0].filter_0());
//prints [5,3,1]
This is a standard way to extend objects and add new methods.
(这是扩展对象和添加新方法的标准方法。)
Lots of libraries do this.(很多图书馆都这样做。)
However, let's look at how for in
works now:(然而,让我们来看看如何for in
现在的工作:)
var listeners = ["a", "b", "c"];
for (o in listeners) {
console.log(o);
}
//prints:
// 0
// 1
// 2
// filter_0
Do you see?
(你有看到?)
It suddenly thinks filter_0 is another array index.(它突然认为filter_0是另一个数组索引。)
Of course, it is not really a numeric index, but for in
enumerates through object fields, not just numeric indexes.(当然,这是不是一个真正的数字指标,但for in
通过对象的字段,而不仅仅是数字索引枚举。)
So we're now enumerating through every numeric index and filter_0
.(所以我们现在枚举每个数字索引和 filter_0
。)
But filter_0
is not a field of any particular array object, every array object has this property now.(但filter_0
不是任何特定数组对象的字段,现在每个数组对象都具有此属性。)
Luckily, all objects have a hasOwnProperty
method, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.
(幸运的是,所有对象都有一个hasOwnProperty
方法,该方法检查该字段是否真正属于对象本身,或者它是否只是从原型链继承而来,因此属于该类型的所有对象。)
for (o in listeners) {
if (listeners.hasOwnProperty(o)) {
console.log(o);
}
}
//prints:
// 0
// 1
// 2
Note, that although this code works as expected for arrays, you should never, never , use for in
and for each in
for arrays.
(请注意,虽然此代码可以按预期的方式运行,但您绝对不应该使用for in
和for each in
for arrays。)
Remember that for in
enumerates the fields of an object, not array indexes or values.(请记住, for in
枚举对象的字段,而不是数组索引或值。)
var listeners = ["a", "b", "c"];
listeners.happy = "Happy debugging";
for (o in listeners) {
if (listeners.hasOwnProperty(o)) {
console.log(o);
}
}
//prints:
// 0
// 1
// 2
// happy