zoukankan      html  css  js  c++  java
  • 关于数组去重的问题--hash表方法

          数组去重有很多方法,效率较高的方法是利用hash表来检测数组中是否有重复项。废话不多说,我查资料编写了如下代码:

      

    function unique(arr){
      var result = [], hash = {};    //定义新数组result ,定义hash.
      for (var i = 0, elem; (elem = arr[i]) !=null; i++) {      //令elem等于传入的数组的某一项并遍历

      console.log(hash[elem]);  //如果在这里加入输出语句,输出hash表中每个项是否存在,输出的结果是4个undefined、true、2个undefined、true,看下面我定义的数组,遍历前四个数的时候,hash表中没有这四个值(1,23,34,45),所以if语句成立,将这四个数push到result中,另这些表中的数都为true。当遍历到第二个1的时候,hash[elem] = true , 所以if语句就不执行了,就不会将重复的数组push进去,也就达到了目的

      if(!hash[elem]){    

          result.push(elem);
          hash[elem] = true;
        }
        console.log(hash[elem])
      }
    console.log(result);   //[1,23,34,45,6,4]
    console.log(hash instanceof Object);    //true
    return result;  
    }

    var arr = [1,23,34,45,1,6,4,23];
    unique(arr);

    我个人是这样理解的,如果有什么偏差,请指出哦~

      

  • 相关阅读:
    Spring Boot 缓存技术:Spring Boot
    Java基础之Iterable接口
    使用sqlyog连接 Mysql 出现1251错误
    IDEA更改主题插件——Material Theme UI详解
    免安装版的Mysql
    使用Nexus搭建Maven私服
    Spring之注解注入bean
    Idea springboot 配置热部署
    Spring Boot 异常处理与单元测试
    Ubuntu20.04在线安装VMware-Tools
  • 原文地址:https://www.cnblogs.com/cy1218/p/5784007.html
Copyright © 2011-2022 走看看