JavaScript數組去重的四種方法

今天,洗澡的想一個有趣的問題,使用js給數組去重,我想了四種方法,雖然今天的任務沒有完成,5555:json

很少說,po代碼:數組

    //方法一:簡單循環去重
    Array.prototype.unique1 = function(){        
        var temp = [];
        for(var i=0; i < this.length; i++){
            if(temp.indexOf(this[i]) == -1){
                temp.push(this[i]);
            }
        }
        return temp;
    }
    //方法二:使用排序後,依次比較的方法
    Array.prototype.unique2 = function(){
        this.sort();
        var temp = [this[0]];
        var j = 0;
        for(var i= 1; i < this.length; i++){
            if(this[i] !== temp[j]){
                temp.push(this[i]);
                j++;
            }
        }
        return temp;
    }
    //方法三:json去重
    Array.prototype.unique3 = function(){
        var temp = {};
        var re = [];
        var j = 0;
        for(var i = 0; i < this.length; i++){
            if(!temp[this[i]]){
                temp[this[i]] = this[i];
                re.push(this[i]);
            }
        }
        return re;

    }
    //方法四:若是數組中的元素是全部不一樣的,那麼數組的第幾個位置i跟indexof得出的值時相同的,不然重複啦!
    Array.prototype.unique4 = function(){
        var temp = [this[0]];
        for(var i = 1; i < this.length; i++){
            if(this.indexOf(this[i]) == i){
                temp.push(this[i]);
            }
        }
        return temp;

    }this

但願你們多多指教,不吝賜教~~prototype

相關文章
相關標籤/搜索