zoukankan      html  css  js  c++  java
  • 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;

        }

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

  • 相关阅读:
    模板汇总 —— 杨式图表
    HDU 6634 网络流最小割模型 启发式合并
    网络流 从0开始学建图
    分层图 单调决策性DP
    模板汇总——笛卡尔树
    Bzoj 2127 happiness 最小割
    manacher --- 暂 旧版本
    Bzoj 3730 震波 动态点分治
    HDU
    Maven私服(Repository Manager)
  • 原文地址:https://www.cnblogs.com/tiffanybear/p/5693616.html
Copyright © 2011-2022 走看看