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

        }

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

  • 相关阅读:
    poj 3280 Cheapest Palindrome(区间DP)
    POJ 2392 Space Elevator(多重背包)
    HDU 1285 定比赛名次(拓扑排序)
    HDU 2680 Choose the best route(最短路)
    hdu 2899 Strange fuction (三分)
    HDU 4540 威威猫系列故事――打地鼠(DP)
    HDU 3485 Count 101(递推)
    POJ 1315 Don't Get Rooked(dfs)
    脱离eclipse,手动写一个servlet
    解析xml,几种方式
  • 原文地址:https://www.cnblogs.com/tiffanybear/p/5693616.html
Copyright © 2020-2023  润新知