zoukankan      html  css  js  c++  java
  • Set,Map与Array,Object对比

    Map与Array

    数据结构横向对比,用Map和Array分别实现最基本的增删改查;

    //增

    {
    let theMap=new Map();
    let theArray=[];
    theMap.set('t',1);
    theArray.push({t:1});
    console.log(theMap);     //Map(1) {"t" => 1}
    console.log(theArray);   //[{t:1}]
    } 

    //删

    theMap.delete('t');
    let index=theArray.findIndex(item=>item.t);
    theArray.splice(index,1);

    //改

    theMap.set('t',2);
    let index=theArray.findIndex(item=>item.t);
    theArray[index]={t:2};
    //或者
    theArray.foreach(item=>item.t?item.t=2:'');

    //查

    theMap.has('t');
    theArray.find(item=>item.t);

    总体来说,Map的操作更方便简洁一些。

    Set与Array

    数据结构横向对比,用Map和Array分别实现最基本的增删改查;

    //增

    {
    let theSet=new Set();
    let theArray=[];
    theSet.add({t:1});
    theArray.push({t:1});
    console.log(theSet);     //{{t:1}}
    console.log(theArray);   //[{t:1}]
    } 

    //删

    theSet.forEach(item=>item.t?theSet.delete(item):'');
    //因为保存的是对象,是引用类型,不能直接通过delete删除,需要用这种方法 
    let index=theArray.findIndex(item=>item.t);
    theArray.splice(index,1);

    //改

    theSet.forEach(item=>item.t?item.t=2:'');
    //因为保存的是对象,是引用类型,不能通过add改,需要用这种方法    
    theAarray.forEach(item=>item.t?item.t=2:'');

    //查

      let set_exist=theSet.forEach(item=>item.t);  
    //因为保存的是对象,是引用类型,通过has查不到,需要用这种方法      
      let array_exist=theArray.find(item=>item.t);

    总体来说,Set储存对象,相对于数组没有明显优势。

    Map,Set与Array

    {
    //因为Set遍历不到对象,所以把对象赋值
      let item={t:1};
      let map=new Map();
      let set=new Set();
      let obj={};
    
      //
      map.set('t',1);
      set.add(item);
      obj['t']=1;
      console.info(obj,map,set);
    
      // 删除
      map.delete('t');
      set.delete(item);
      delete obj['t'];
      console.info(obj,map,set);
    
      //
      map.set('t',2);
      item.t=2;
      obj['t']=2;
      console.info(obj,map,set);
    
      //
      console.info({
        map.has('t'),
        set.has(item),
        't' in obj
      })
    }

    Map最好用,Set唯一性较好

  • 相关阅读:
    吃了很多杏仁,干果的祸
    persistent.xml hibernate 利用sql script 自定义生成 table 表
    JSF dataTable 添加列 动态创建数据表 列
    java 和 mysql 获取周 星期 的第一天 最后一天 或者 月的 日期(字符串转日期,日期转字符串,日期加减)
    JSF JQUERY 使用datepicker
    JPA mysql wildfly jboss 存储时乱码
    JPA事务总结
    这样吃饭,其实是在喂养身体里的“癌细胞”
    Mysql 列转行统计查询 、行转列统计查询
    mysql 生成排名字段
  • 原文地址:https://www.cnblogs.com/sunmarvell/p/9134484.html
Copyright © 2011-2022 走看看