zoukankan      html  css  js  c++  java
  • 数组去重复算法

    1.遍历法

      var ary=[1,23,12,12,1,12,32,1,1];
      function noRepetition(ary){
    //    1.创建新数组
        var newAry=[];
    //    2.遍历老数组,拿到每个值,看新数组有这个值吗,没有添加进去,
        for(var i=0;i<ary.length;i++){
          var cur=ary[i];
          if (newAry.indexOf(cur)==-1){     indexOf IE8以前不支持,
            newAry.push(cur)
          }
        }
    //    3.返回新的数组
        return newAry;
      }
      var result=noRepetition(ary);
      console.log(result)                 
    //方法不改变元素组

    兼容版:

    //兼容IE低版本的indexOf方法
    if(!Array.prototype.indexOf){ Array.prototype.indexOf=function(para){ var result=-1; var temp=para; if (!this.length){ return result } // 谁调用我,我就便利谁 for(var i=0;i<this.length;i++){ var cur=this[i] if (cur==temp){ result=temp; break; } } return result } }

    2.对象键值对

      var ary=[1,23,12,12,1,12,32,1,1];
    function noRepetition(ary){
      var obj={};
    //  1.拷贝一份原数组
      var temp=ary.slice(0);
    //  2.遍历
      for(var i=0;i<temp.length;i++){
        var cur=temp[i];
    //    如果对象obj[cur]==undefined表示,对象没有该属性,添加该属性
        if (!obj[cur]){
          obj[cur]=cur;
        }else{
    //      否则,证明对象中有该属性,temp数组删除重复元素
          temp.splice(i,1);
          i--;
        }
      }
      return temp;
    }
      var result=noRepetition(ary);
      console.log(result)

    3.排序去重复法

      var ary=[1,1,2,1,33,22,75,15,2,2,1,2,1,3,4,5,5,75];
      function noRepetition(ary){
        var result=[];
    //    1.排序
        var temp=ary.sort(function(a,b){
          return a-b
        });
    //    2.遍历排好序的数组
        for(var i=0;i<temp.length;i++){
    //      3.当 当前值不等于后一项的值时
          if (temp[i]!==temp[i+1]){
    //        4.空数组中添加当前项
    //        注意,当我们最后一项时,他的后一项时undefined的,所以最后一项可以添加进来
            result.push(temp[i])
          }
        }
        return result
      }
      console.log(noRepetition(ary))
  • 相关阅读:
    ckplayer 一个不错的网页视频播放器
    onbeforeunload与a标签在IE中的冲突
    使用ckeditor 4.x 时遇到的问题及解决办法
    虚方法和重写方法的继承特性
    接口成员的访问
    基本框架(html)
    学习this关键字
    静态类
    方法参数
    Kubernetes之网络探究
  • 原文地址:https://www.cnblogs.com/liangfc/p/8695741.html
Copyright © 2011-2022 走看看