数组去重复是js中常用的方法,归纳了四种如下:
1. for + indexOf 去重复
var arr = [3,5,5,4,1,1,2,3,7,2,5];
var target = [];
for(var i=0,len=arr.length;i<len;i++){
if( target.indexOf(arr[i])==-1 ){
target.push(arr[i]);
}
};
console.log(target);
2. forEach + indexOf 去重复
var arr = [3,5,5,4,1,1,2,3,7,2,5];
var target = [];
arr.forEach(function(val){
if(this.indexOf(val)==-1){
this.push(val);
};
},target);
console.log(target);
3.原型对象 prototype + for + indexOf 去重复
Array.prototype.quchong = function(){
var target = [] ;
for(var i=0,len=this.length;i<len;i++){
if(target.indexOf(this[i])==-1){
target.push(this[i]);
}
};
return target;
};
var arr = [3,5,5,4,1,1,2,3,7,2,5];
console.log(arr.quchong());
4.原型对象 prototype + forEach + indexOf 去重复
Array.prototype.quchong = function(){
var target = [];
this.forEach(function(val){
if(this.indexOf(val)==-1){
this.push(val);
}
},target);
return target;
};
var arr = [3,5,5,4,1,1,2,3,7,2,5];
console.log(arr.quchong());
运行结果: