JS数组去重的两种方式

1  数组去重

let arr = [1,2,3,2,5,3,1,NaN, null, false, undefined, false, NaN, null, undefined];

  ES5实现

// foreach循环
deleteCopy(arr){      
  let obj={};
  let newArr = [];
  // 利用对象的key值  
  arr.forEach((item,index) => { 
    if(!obj[item]){
      obj[item] = true;
      newArr.push(item);
    }             
  });
  console.log(newArr); 
  // [1, 2, 3, 5, NaN, null, false, undefined]
},

  ES6  

// set返回的是一个对象,该用Array.form,可以把类数组对象、可迭代对象转化为数组
deleteCopyES6(arr){
  console.log(Array.from(new Set(arr)))
  // [1, 2, 3, 5, NaN, null, false, undefined]
},

  

猜你喜欢

转载自www.cnblogs.com/webfont-yxw/p/11735764.html