js数组去重复项

来源:互联网 发布:詹姆斯06年数据 编辑:程序博客网 时间:2024/06/06 23:33

1.天书

Array.prototype.unique2 = function () {    return this.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");}

2.使用对象的【hasOwnProperty】方法

Array.prototype.unique3 = function() {    var temp = {}, len = this.length;    for(var i=0; i < len; i++)  {        var tmp = this[i];        if(!temp.hasOwnProperty(tmp)) {            temp[this[i]] = "my god";        }    }      len = 0;    var tempArr=[];    for(var i in temp) {        tempArr[len++] = i;    }    return tempArr;}
3.先排序,前项比后项

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

4.下面是以前经常用的,效率也很好。有点想hash表的感觉。

我很喜欢这个,由于对js不够熟悉,看了很长时间才看明白

Array.prototype.unique5 = function() {    var res = [], hash = {};    for(var i=0, elem; (elem = this[i]) != null; i++)  {//判断hash里面有没有这个值        if (!hash[elem])        {//hash里面没有这个值时,将数据取出来,赋值给res数组,同时将这个值保存到hash,//下次如果hash里有这个值时,上面if就知道hash里已经有值啦,不用再保存了            res.push(elem);            hash[elem] = true;        }    }    return res;}
作者:Novus 
出处:http://www.cnblogs.com/novus/ 
本文版权归作者和博客园共有,欢迎任何形式的转载,但请务必注明出处。


0 0
原创粉丝点击