当使用 for..in 循环以及我添加到 array.prototype 的函数时,for..in 也会循环遍历所有这些函数。
The JavaScript for/in statement loops through the properties of an object
但是我如何添加到数组原型(prototype)而不在 for..in 中被触发?
示例代码:
Array.prototype.sum = function (prop) {
// Do something
}
for (item in myArray) {
// Would actually loop myArray.length times + 1 for the 'sum'
}
我正在使用一个使用 for..in 循环的库,我无法更改它。
最佳答案
But how do I add to array prototype without it being triggered in the for..in?
通过将其添加为不可枚举 属性,通过 Object.defineProperty
.不可枚举是默认值,因此:
Object.defineProperty(Array.prototype, "sum", {
value: function() {
// ...implementation of sum
}
});
...但如果我们想要明确,我们将有 enumerable: false
:
Object.defineProperty(Array.prototype, "sum", {
enumerable: false, // <== Not necessary, false is the default
value: function() {
// ...implementation of sum
}
});
实例:
Object.defineProperty(Array.prototype, "sum", {
value: function() {
return this.reduce(function(acc, value) {
return acc + value;
}, 0);
}
});
var a = [1, 2, 3];
snippet.log("a.sum() = " + a.sum());
var key;
for (key in a) {
snippet.log("key = " + key);
}
snippet.log("Note that 'sum' did not show up as a key");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
所有现代浏览器都支持 Object.defineProperty
,它是 2009 年发布的第 5 版规范的一部分。IE8 不支持,因为它早于规范。
旁注:我不建议使用 for-in
循环遍历数组,无论是将非入口属性添加到 Array.prototype
(还是数组本身) 或不。我在 this answer 中推荐各种替代方案.但是你说过你正在使用一个库来执行它并且没有必要的 hasOwnProperty
检查(这使它成为一个写得不好的库)并且不能改变它,所以.. . 以上是您如何添加到 Array.prototype
而没有添加显示在 for-in
中。
关于javascript - 如何添加 "doesn' t 触发“for..in”的新数组方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32478264/