javascript数组去重

直接上代码:

Array.prototype.distinct = function () { 
    var newArr = [],obj = {}; 
    for(var i=0, len = this.length; i < len; i++){ 
        if(!obj[typeof(this[i]) + this[i]]){ 
            newArr.push(this[i]); 
            obj[typeof(this[i]) + this[i]] = 'new'; 
        } 
    } 
    return newArr; 
} 

加强版:

Array.prototype.distinct = function () { 
    var sameObj = function(a, b){ 
        var tag = true; 
        if(!a || !b) return false; 
        for(var x in a){ 
            if(!b[x]) return false; 
            if(typeof(a[x]) === 'object'){ 
                tag = sameObj(a[x],b[x]); 
            } else { 
                if(a[x]!==b[x]) 
                return false; 
            } 
        } 
        return tag; 
    } 
    var newArr = [], obj = {}; 
    for(var i = 0, len = this.length; i < len; i++){ 
        if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){ 
        newArr.push(this[i]); 
        obj[typeof(this[i]) + this[i]] = this[i]; 
        } 
    } 
    return newArr; 
} 

 

posted @ 2013-10-11 14:00  breezefeng  阅读(277)  评论(0编辑  收藏  举报