数组去重(map和set)

//[false,true,undefined,null,NaN,0,0,1,1,{},{},'a','a',NaN] 为Array对象添加一个去重方法(仅限			  Map和Set)
  //[false, true, undefined, null, NaN, 0, 1, {…}, {…}, "a"]
  let arr = [false,true,undefined,null,NaN,0,0,1,1,{
    
    },{
    
    },'a','a',NaN]
  Array.prototype.unique1 = function () {
    
    
    if(!Array.isArray(this)) return false
    return [...new Set(this)]
  }
  console.log(arr.unique1());
  Array.prototype.unique2 = function () {
    
    
    if(!Array.isArray(this)) return false
    let newArr = []
    let temMap = new Map()
    for(let i=0;i<this.length;i++) {
    
    
      if(!temMap.has(this[i])) {
    
    
          temMap.set(this[i],1)
          newArr.push(this[i])
      }
    }
    return newArr
  }
  console.log(arr.unique2());

猜你喜欢

转载自blog.csdn.net/qq_44540152/article/details/120054356