js 数组去重复的方法

2017-12-12 21:10:39   1549

数组去重复是js中常用的方法,归纳了四种如下:

1. for + indexOf  去重复

var arr = [3,5,5,4,1,1,2,3,7,2,5];
2       var target = [];
3       for(var i=0,len=arr.length;i<len;i++){
4         if( target.indexOf(arr[i])==-1 ){
5           target.push(arr[i]);
6         }
7       };
8       console.log(target);

2. forEach + indexOf 去重复

  var arr = [3,5,5,4,1,1,2,3,7,2,5];
2       var target = [];
3       arr.forEach(function(val){
4         if(this.indexOf(val)==-1){
5           this.push(val);
6         };
7       },target);
8       console.log(target);

3.原型对象 prototype + for + indexOf 去重复

   Array.prototype.quchong = function(){
 2         var target = [] ;
 3         for(var i=0,len=this.length;i<len;i++){
 4           if(target.indexOf(this[i])==-1){
 5             target.push(this[i]);
 6           }
 7         };
 8         return target;
 9       };
10       var arr = [3,5,5,4,1,1,2,3,7,2,5];
11       console.log(arr.quchong());


4.原型对象 prototype + forEach + indexOf 去重复

  Array.prototype.quchong = function(){
 2         var target = [];
 3         this.forEach(function(val){
 4           if(this.indexOf(val)==-1){
 5             this.push(val);
 6           }
 7         },target);
 8         return target;
 9       };
10       var arr = [3,5,5,4,1,1,2,3,7,2,5];
11       console.log(arr.quchong());