我想在数组上添加“插入”方法。 所以我这样做:
> 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);
}
});
关于javascript - 向 Array.prototype 添加方法,没有副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387766/