将方法添加到Array.prototype,没有副作用

Ton*_*ada 2 javascript prototype for-in-loop

我想在Arrays上添加一个"插入"方法.所以我这样做:

> Array.prototype.insert = function(index, element){
    this.splice(index, 0, element);
};
Run Code Online (Sandbox Code Playgroud)

它有效:

> a = [1,2,3]
[1, 2, 3]
> a.insert(0, 4)
undefined
> a
[4, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

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

> 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);
}
Run Code Online (Sandbox Code Playgroud)

此行为不是打算,并打破我使用的其他库.这有什么优雅的解决方案吗?

p.s*_*w.g 8

Object.defineProperty虽然有效但旧版浏览器不支持它.(兼容性表)

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

示范