es6解读2:数据结构介绍

作者: cd72c1240b33 | 来源:发表于2017-07-13 22:12 被阅读104次

    Set的用法:set数据类型的元素,必须是唯一的;添加重复的元素不会报错,只是不会生效;

    • 他在转换元素的时候,不会进行数据类型的隐式转换;
    • 可以用它来去重;
        let arr=[1,2,3,4,2,1,2,3,2];
        let list=new Set(arr);
        console.log(list)
    
    • Set()实例的方法:
      1、add() 添加元素
      2、delete() 移出
      3、clear() 清空
      4、has() 判断元素中是否有某个内容
        let arr=['add','delete','clear','has'];
        let list=new Set(arr);
        console.log(list.has('add'))
        console.log(list.delete('add'),list)
        console.log(list.clear(),list)
        ```
    - Set实例的遍历
    
    
    //1:遍历属性名
    for(let key of list.keys()){
        console.log(key)
    }
    //2:遍历属性值
    for(let value of list.values()){
        console.log(value)
    }
    //3:遍历属性名和属性值
    
    for(let [key,value] of list.entries()){
        console.log(key,value)
    }
    ```
    
    • Set实例的 forEach
        list.forEach(function (item) {
            console.log(item)
        })
        ```
    #### WeakSet的用法
    - let weakList=new WeakSet()
    - WeakSet和set的区别:
        1、WeakSet和set支持的数据类型不一样;
        2、WeakSet中的对象都是若引用;不会检测地址是否被垃圾回收掉;
        3、他的属性,没有size属性,没有clear方法,不能遍历;
    
    #### Map的用法
    - map的属性名可以是任意数据类型;
    - map增加值,用set,获取值用get
    - map的两种写法
    
    

    //第一种写法:
    let map=new Map();
    let arr=['123'];
    map.set(arr,456);
    console.log('map',map,map.get(arr))

    //第二种写法
    let map=new Map([['a',123],['b',456]])
    console.log(map)

    - map常用的属性值和方法
        + map.size 长度
        + set设置,get获取
        + delete() 删除; clear()清空
    
    #### WeakMap的用法
    - weakMap和map的区别:
        + 前者接收的值只能是对象
        + 他没有set属性,不能使用clear()
        + 不能遍历; 跟weakSet和set的区别一样;
    

    相关文章

      网友评论

      本文标题:es6解读2:数据结构介绍

      本文链接:https://www.haomeiwen.com/subject/plvghxtx.html