js数组去重的几种方法

   var arr = [42123,123,3214,123,12321,123,131,1232,2,21,21,3132,2,312,3];
//验证时请把其他方法注释起来
way1
for(var i = 0;i < arr.length-1;i++){ for(var j = i+1;j < arr.length;j++){ if(arr[i] == arr[j]){ arr.splice(j,1); j--; } } } console.log(arr) way2 for(var i = 0;i < arr.length;i++){ if(arr.indexOf(arr[i]) != i){ arr.splice(i,1); i--; } } console.log(arr) way3 var srr1 = arr.filter(function(value,index,self){ return self.indexOf(value) === index }) console.log(srr1) console.log(arr) way4 var arr2 = []; for(var i = 0;i < arr.length;i++){ if(arr.indexOf(arr[i]) == i){ arr2.push(arr[i]); } } console.log(arr2) way5 var obj = {}; var arr2 = []; for(var i = 0;i < arr.length;i++){ if(!obj[arr[i]]){ obj[arr[i]] = true; arr2.push(arr[i]); } } console.log(arr2) way6 var arr2 = []; for(var i = 0; i < arr.length;i++){ if(arr2.indexOf(arr[i]) == -1){ arr2.push(arr[i]); } } console.log(arr2) way7 var arr2 = new Set(arr); console.log(arr2) //arr2是对象 var arr2 = []; for(var i = 0;i < arr.length;i++){ var arr3 = []; for(var j = i+1;j < arr.length;j++){ if(arr[i] == arr[j]){ arr3.push(j); } } if(arr3.length == 0){ arr2.push(arr[i]); } } console.log(arr2) way8 for(var i = 0;i < arr.length;i++){ for(var j = i+1;j < arr.length;j++){ if(arr[i] == arr[j]&&i != j){ arr.splice(j,1); } } } console.log(arr)

 

posted on 2019-09-21 08:37  四月as谎言  阅读(97)  评论(0编辑  收藏  举报

导航