我不小心使用了这样的迭代
for (var key in arr)
{
alert(key);
}
得到的输出引发了一些问题。 (我想遍历 JSON,所以我使用了 'key' - 在这种情况下,索引的 'i' 会更合适,毫无疑问 :-)
第一个输出是索引(如“0”、“1”等)——仍然没有问题——但最后它抛出了我的 Array.prototypes 的名称,我在代码的其他地方声明了。原型(prototype)如
Array.prototype.lastIndex = function(){
return this.length - 1;
}
它只抛出“lastIndex”。
我不明白的是:我自己的非固有原型(prototype)是否与 JS 固有原型(prototype)(如 splice()、slice() ...)不同?
并且:为什么它会抛出它们?它们是 Array.prototype 的一部分,但不是特定 Array 对象的一部分!?
提前致谢!
最佳答案
当您将属性附加到对象时,默认情况下,该属性将
可枚举
。如果属性是可枚举的,
for..in
将选取它。
因此,当您使用 for..in
迭代数组对象时,它首先给出当前对象中的所有可枚举属性。然后,它沿原型(prototype)链向上,给出相应对象的所有可枚举属性。因此,在您的情况下,它沿链向上移动并在 Array
的原型(prototype)中找到一个名为 lastIndex
的可枚举属性,并将其包含在迭代中。
如果你用enumerable: false
定义它,像这样
Object.defineProperty(Array.prototype, 'lastIndex', {
value: function() {
return this.length - 1;
},
enumerable: false
});
它不会出现在 for..in
迭代中。引用 MDN documentation for enumerable
attribute ,
The
enumerable
property attribute defines whether the property shows up in afor...in
loop andObject.keys()
or not.
关于javascript - JS "for (var key in arr)"> 抛出我自己的 Array.prototypes,但不是固有的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877705/