javascript - 如何添加 "doesn' t 触发“for..in”的新数组方法?

标签 javascript arrays

当使用 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/

相关文章:

javascript - Express js app.get 回调中如何获取多个独立的响应数据

javascript - 使用 ngserve 启动服务器时出现 NPM 错误

arrays - 数组中大小为 k 的最小词典子序列

c++ - 为什么我在 ‘]’ token 之前得到数组绑定(bind)不是整数常量,即使全局声明了大小?

PHP:当关联数组位于函数内并且该函数被多次调用时,它是否会多次创建该数组?

javascript - 等待函数完成的 setInterval 的替代方法

javascript - 将数据从 php 传递到 javascript 以用于混合应用程序

javascript - 如何使用数组值向对象添加键?

python - 如何在 Python 中创建二维数组

java - 数组自增语法