问题描述
所以我在IE8中使用它:
So I am using this in IE8:
var hi=["hi", "lo", "foo", "bar"];
for(i in hi){console.log(i)};
//WTF is that indexOf i value?
LOG: 0
LOG: 1
LOG: 2
LOG: 3
LOG: indexOf
undefined
在Chrome和其他人中,我只会得到0-3,没有神秘的indexOf。为什么以及修复了什么?
In chrome and others, I'll just get 0-3, no mysterious "indexOf" thing. Why and what's the fix?
推荐答案
不要在$ c中使用 ... $ c>用于数组。在这种情况下,最好使用传统的
for
循环。
原因是因为 for ... in
将数组视为一个对象,因此属性如 indexOf
或 length
可能包含在循环中。 循环的正常仅处理数字键,因此避免了这个问题。
The reason is because for...in
looks at the array as an object, and therefore properties like indexOf
or length
may be included in the loop. The normal for
loop only deals with numeric keys, so this problem is avoided.
一边注意,在迭代普通对象时也会显示不需要的属性(正如其他人所说,添加到对象原型的属性将会显示)。您可以通过以下方式编写 for ... in
循环来解决这个问题:
On a side note, unwanted properties could show up when iterating over plain objects as well (as others have noted, properties you add to the object's prototype will show up). You can get around this by writing your for...in
loops this way:
var obj = { ... };
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var item = obj[prop];
...
}
}
要清楚虽然:你仍然不应该在数组上使用这个方法。
To be clear though: you still shouldn't use this method on arrays.
这篇关于IE8 for ...在枚举器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!