[JS] 为数组原型扩展方法引发的xxx案
相信大家都看过类似的在js中扩展 数组的 remove 方法,这个有个巨坑
Array.prototype.remove = function(item){
var idx = this.indexOf(item);
if(idx >= 0){
return this.splice(idx,1);
}
return null;
}
调用的时候:
var arr = ['a','b','c'];
arr.remove('b');
console.log(arr)
如果只是这么用,没有任何问题,因为结果确实是删掉了,也能达到想要的目的。但是,执行下列代码的时候:
for(var i in arr){
console.log(key)
}
//结果得到:
0
1
remove
你会发现最后一个元素是一个remove,很明显,就是我们自己扩展的那个方法,达不到我们预期的结果。看来这是用原型对象来扩展方法后用for-in遍历会出现这种坑,经过修改我试着采用ES5中的defineProperty来实现这个效果。代码如下:
Object.defineProperty(Array.prototype, 'remove', {
value: function (item, idx) {
return idx = this.indexOf(item), idx > -1 ? this.splice(idx, 1) : null;
}
});