博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js去除数组中的重复项
阅读量:7001 次
发布时间:2019-06-27

本文共 680 字,大约阅读时间需要 2 分钟。

js的Array类型并没有提供去重复的方法,如果要把数组的重复元素干掉,可以自己对其进行扩展。

第一种思路是先把数组进行排序,然后比较前后元素是否相等,相等则continue,否则就记录到返回值中:

Array.prototype.unique = function () {    var temp = [];      this.sort();      var len = this.length;      for(i = 0; i < len; i++) {          if( this[i] == this[i+1]) {            continue;        }        temp[temp.length]=this[i];      }      return temp;}

另外,也可以使用js动态语言的特性,使用一个动态更新的对象来判断元素是否重复:

function unique(arr) {    var result = [], hash = {};    for (var i = 0, elem; (elem = arr[i]) != null; i++) {        if (!hash[elem]) {            result.push(elem);            hash[elem] = true;        }    }    return result;}

 

转载于:https://www.cnblogs.com/lswit/p/5311451.html

你可能感兴趣的文章