javascript 数组去重

摘自 带刀http://stylechen.com/

对于数组去重首先想到的是两重循环。

 1     Array.prototype.distinct = function(){
 2         var arr = [],
 3              len = this.length;
 4 
 5         for ( var i = 0; i < len; i++ ){
 6             for( var j = i+1; j < len; j++ ){
 7                 if( this[i] === this[j] ){ // 有相同的就跳过,对后面的数组继续循环
 8                     j = ++i; 
 9                 }
10             }
11             arr.push( this[i] );
12         }
13         return arr;
14     };

不过遇到大的数组效率就很低下了。

于是弄了另外种方法。

1     Array.prototype.delRepeat = function(){
2         var newArr = [],tempObj = {};
3         for(var i = 0; item; (item=this[i])!=null;i++){
4             if(!tempObj[item]){
5                 newArr.push(this[i]);
6                 tempObj[item] = true;
7             }
8         }
9     }

不过 对于 [1,"1"]这种数组不给力。于是改进了下。

        Array.prototype.delRepeat = function(){
        var newArr = [],
            tempObj = {};
        for(var i =0, item; (item = this[i])!= null;i++){
            if(tempObj[item] !== this[i]){
                newArr.push(this[i]);
                tempObj[item] = item;
            }
        }
        return newArr;
    }

 

posted @ 2012-05-27 15:55  liyatang  阅读(399)  评论(3编辑  收藏  举报