JavaScript数组去重的四种方法

今天,洗澡的想一个有趣的问题,使用js给数组去重,我想了四种方法,虽然今天的任务没有完成,5555:

不多说,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;

    }

希望大家多多指教,不吝赐教~~

原文地址:https://www.cnblogs.com/tiffanybear/p/5693616.html