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

时间:2020-09-14 09:37:14   收藏:0   阅读:142

题目描述

为 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
}

  

原文:https://www.cnblogs.com/banyouxia/p/13664752.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!