首先来看一段神奇的代码
Array.prototype.remove = function(item){
var idx = this.indexOf(item);
if(idx >= 0){
return this.splice(idx,1);
}
return null;
}
var arr = [1,3,5,2,4];
console.log(arr.remove(3),arr);
for(var i in arr){
if(typeof arr[i] === 'number'){
console.log(arr[i]);
}
else{
console.log([i,'什么鬼']);
}
}
结果:
[ 3 ] [ 1, 5, 2, 4 ]
1
5
2
4
[ ‘remove’, ‘什么鬼’ ]
没错啊 是吧 为啥最后一个元素是一个remove方法呢,得不到我们预期的结果啊,用原型对象来扩展方法后用for-in遍历会出现这种坑。一般来说for in是用来遍历对象属性的,而数组还是要用for来遍历。所以经过修改我试着采用ES5中的defineProperty来实现这个效果。代码如下:
Object.defineProperty(Array.prototype,'remove',
{value:function(item){
var idx = this.indexOf(item);
if(idx >= 0){
return this.splice(idx,1);
}
return null;
}
});
var arr = [1,3,5,2,4];
console.log(arr.remove(3),arr);
for(var i in arr){
if(typeof arr[i] === 'number'){
console.log(arr[i]);
}
else{
console.log([i,'什么鬼']);
}
}
结果:
[ 3 ] [ 1, 5, 2, 4 ]
1
5
2
4