我想在数组上添加“插入”方法。
所以我这样做:
> 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty有效,但旧版浏览器不支持它。 (兼容性表 http://kangax.github.io/es5-compat-table/#Object.defineProperty)
Object.defineProperty(Array.prototype, 'insert', {
enumerable: false,
value: function(index, element){
this.splice(index, 0, element);
}
});
示范 http://jsfiddle.net/GV5Z4/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)