javascript - 向 Array.prototype 添加方法,没有副作用

标签 javascript prototype for-in-loop

我想在数组上添加“插入”方法。 所以我这样做:

> Array.prototype.insert = function(index, element){
    this.splice(index, 0, element);
};

它有效:

> a = [1,2,3]
[1, 2, 3]
> a.insert(0, 4)
undefined
> a
[4, 1, 2, 3]

但是有一个不良的副作用:

> for (i in a){console.log(i)}
0
1
2
3
insert

> for (i in a){console.log(a[i])}
4
1
2
3
function (index, element){
    this.splice(index, 0, element);
}

此行为并非有意为之,并且会破坏我使用的其他库。 有什么优雅的解决方案吗?

最佳答案

Object.defineProperty有效,但旧版浏览器不支持它。 (compatibility table)

Object.defineProperty(Array.prototype, 'insert', {
  enumerable: false,
  value: function(index, element){
    this.splice(index, 0, element);
  }
});

Demonstration

关于javascript - 向 Array.prototype 添加方法,没有副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387766/

相关文章:

javascript - IE11 javascript重定向历史问题

javascript - 如何使用 javascript(原型(prototype))继承正确派生具有私有(private)变量的对象

javascript - 当 thisArg 与后续参数属于同一个数组时,function.prototype.apply 如何工作

Python for-in 循环前面有一个变量

ios - 如何在swift中使用for in循环递减条件?

javascript - 在鼠标悬停和鼠标移出时显示隐藏 div

javascript - 监听不同元素上的多个触发事件后触发函数

javascript - 对于 JavaScript 的继承,是引用父类的原型(prototype)还是复制父类的原型(prototype)更好?

javascript - 循环遍历对象以输出图标 javascript

javascript - 如何通过一个按钮在 jQuery 中将 'replace' 数字与 'x' s' 进行比较?