js 为 Array 对象添加一个去除重复项的方法

题目描述

为 Array 对象添加一个去除重复项的方法

输入

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]

输出

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']

解决

Array.prototype.uniq = function () {
   let res = []
      let hasNaN = false
      this.forEach(e => { // 循环数组
          if(res.indexOf(e) === -1) { // res中没有就添加
            if(e !== e) { // 判断是否为NAN,因为精度的原因,NaN === NaN返回false
              if(!hasNaN) {
                res.push(e)
                hasNaN = true
              }
            } else {
              res.push(e)
            }
          }
      })
      return res
}

  

posted @ 2020-09-14 07:47  半忧夏  阅读(702)  评论(0编辑  收藏  举报