您的位置:首页 > Web前端 > JavaScript

javascript的4种数组去重(包含 es6 去重写法)

2020-07-14 06:08 197 查看

1: 第一种

  Array.prototype.unique1= function(){

    var newArr =[];

    for(var i=0; i< this.length; i++){

      if( newArr.indexof(this[i])  == -1 ){

        newArr.push(this[i])

      }  

    }

    return newArr

  }  

 

2: 第二种

  

  Array.prototype.unique2 = function(){

    var newArr =[] , obj = {} ;

    for(var i=0; i< this.length; i++){

      if( !obj[this[i]] ){

        obj[this[i]] = true;

        newArr.push(this[i])

      }  

    }

    return newArr;

  }  

3: 第三种方式

  Array.prototype.unique3 = function(){

    var newArr =[this[0]] ;

    for(var i=1; i< this.length; i++){

      if(this.indexof(this[i]) == i ) newArr.push(this[i])

    }

    return newArr;

  } 

4:  第四种方式    //  这是es6种的最新写法,如果你的程序支持es6,你可大胆使用

  newArr = [...new set(oldArr)]

转载于:https://www.cnblogs.com/Glen1021/p/6923506.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: