题目描述

为 Array 对象添加一个去除重复项的方法
输入例子:
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN].uniq()

输出例子:
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
Array.prototype.uniq = function () {
    var resArr=[];
    var flag = true;
    for(var i=0;i<this.length;i++){
        if(resArr.indexOf(this[i])==-1){//indexOf 如果新建的数组里没有this[i]
            if(this[i]!=this[i]){//因为NaN!=NaN 所以这里要判断NaN
                if(flag){
                    resArr.push(this[i]);
                    flag = false;
                }
            }else{
                resArr.push(this[i]);
            }
        }
    }
    return resArr;
}

 

相关文章:

  • 2021-09-09
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案