好程序员分享JavaScrip数组去重操作实例小结

好程序员分享JavaScrip数组去重操作实例小结这篇文章主要介绍了JavaScrip数组去重操作,结合实例形式总结分析了javascript针对数组的遍历、判断、去重等相关操作技巧,需要的朋友可以参考下

本文实例讲述了JavaScrip数组去重操作。分享给大家供大家参考,具体如下:

内置的for-of方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<script>

var arr=[2,1,1,3,'','','e','e',true,'true',true,false,false,'false',undefined,'undefined',undefined,null,'null',null];

function uniqueUseForOf(array) {

  const temp = []; //一个临时数组

  // 传入值必须存在,且长度小于等于1的时候直接返回数组

  if (array && array.length <= 1) {

    return array;

  } else {

    //遍历当前数组

    for (let x of array) {

      temp.indexOf(x) === -1 ? temp.push(x) : '';

    }

  }

  return temp;

}

uniqueUseForOf(arr);

console.log(uniqueUseForOf(arr))

</script>

内置的forEach方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<script>

var arr=[3,1,1,3,'','','e','e',true,'true',true,false,false,'false',undefined,'undefined',undefined,null,'null',null];

function uniqueUseForEach(array) {

  // 传入值必须存在,且长度小于等于1的时候直接返回数组

  if (array && array.length <= 1) {

    return array;

  } else {

    var temp = []; //一个临时数组

    //遍历当前数组

    array.forEach(function (value, index) {

      temp.indexOf(value) == -1 ? temp.push(value) : '';

    })

    return temp;

  }

}

uniqueUseForEach(arr);

console.log(uniqueUseForEach(arr))

</script>

万能的for方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<script>

var arr=[1,1,'','','e','e',true,'true',true,false,false,'false',undefined,'undefined',undefined,null,'null',null];

function uniqueUseFor(array) {

  var temp = []; //一个临时数组

  //遍历当前数组

  for (var i = 0, j = array.length; i < j; i++) {

    //很直白,新数组内判断是否有这个值,没有的情况下,就推入该新数组

    temp.indexOf(array[i]) === -1 ? temp.push(array[i]) : '';

  }

  return temp;

}

uniqueUseFor(arr);

console.log(uniqueUseFor(arr))

</script>

第一种方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<script>

var arr = [1, 2, 3, 4, 1, 2, 4, 5, 6];

console.log(arr);

Array.prototype.unique = function() {

  var n = [this[0]]; //结果数组

  for(var i = 1; i < this.length; i++) //从第二项开始遍历

  {

    //如果当前数组的第i项在当前数组中第一次出现的位置不是i,

    //那么表示第i项是重复的,忽略掉。否则存入结果数组

    if(this.indexOf(this[i]) == i) n.push(this[i]);

  }

  return n;

};

console.log(arr.unique());

</script>

第二种方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<script>

var arr = [1,2,3,4,1,2,4,5,6];

console.log(arr);

Array.prototype.unique = function()

{

  var n = {},

    r = []; //n为hash表,r为临时数组

  for (var i = 0; i < this.length; i++) { //遍历当前数组

    if (!n[this[i]]) { //如果hash表中没有当前项

      n[this[i]] = true; //存入hash表

      r.push(this[i]); //把当前数组的当前项push到临时数组里面

    }

  }

  return r;

};

console.log(arr.unique());

</script>

猜你喜欢

转载自www.cnblogs.com/gcghcxy/p/11227251.html
今日推荐