文章出處

直接上代碼:

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; 
} 

 


文章列表


不含病毒。www.avast.com
全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()