向 Array.prototype 添加方法,没有副作用 [英] Add methods to Array.prototype, without the side effects
本文介绍了向 Array.prototype 添加方法,没有副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在数组上添加一个插入"方法.所以我是这样做的:
I'd like to add an "insert" method on Arrays. So I'm doing it like this:
> 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]
但是有一个不希望的副作用:
But there's an undesired side effect:
> 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);
}
这种行为不是故意的,会破坏我使用的其他库.对此有什么优雅的解决方案吗?
This behavior is not intended and breaks other libraries that I use. Is there any elegant solution for this?
推荐答案
Object.defineProperty
有效,但旧浏览器不支持.(兼容性表)
Object.defineProperty(Array.prototype, 'insert', {
enumerable: false,
value: function(index, element){
this.splice(index, 0, element);
}
});
这篇关于向 Array.prototype 添加方法,没有副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文