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
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM