es6之数据结构

1、set的用法

用add方法添加元素,添加的数组不可重复。

可利用set类型添加元素不重复的功能,给数组完成去重的功能

size属性用于获取set元素的长度

{
    let list =new Set();
    list.add(5);
    list.add(7);
    console.log("size",list.size);  //2
}

{
    let arr=[1,2,3,4,5];
    let list=new Set(arr);
    console.log(list.size); //2
}

{
    let list=new Set();
    list.add(1);
    list.add(2);
    list.add(1);

    console.log("list",list) // {1,2}
}

 但是set不会进行数据类型的转换

//set 不会进行数据类型的转换
    let arr=[1,2,3,12,1,2,"2"];
    let list2=new Set(arr);
    console.log("list2",list2); //{1, 2, 3, 12, "2"}

 set的一些方法

.add()添加

.delete() 删除

.clear() 清除

.has()  是否有

let arr=["add","delete","clear","has"];
    let list=new Set(arr);
    console.log(list.has("add"));
    console.log("delete",list.delete("add"),list);
    list.clear();
    console.log("list",list);

set的遍历(key值==value值)

    //读取
    console.log("set的读取");
    let arr=["add","delete","clear","has"];
    let list=new Set(arr);
    for(let index of list.keys()){
        console.log("keys",index);
    }
    for(let value of list.values()){
        console.log("value",value);
    }
    for(let [index,value] of list.entries()){
        console.log("entries",index,value);
    }  

  

weakSet 

//weakSet
    /*
    * weakSet是一个弱引用,只能是一个对象,没有size属性
    * 没有clear方法
    * 没有遍历属性
    * */
    let weakList=new WeakSet();
    let arg={};
    weakList.add(arg);
    console.log("weakList",weakList);

 

map

{
    //map的定义方法1
    let map=new Map();
    let arr=["123"];
    map.set(arr,456);
    console.log("map",map,map.get(arr));
}

{  //map的定义方法2
    let map=new Map([["a",123],["b",456]]);
    console.log("map args",map);

    //map的方法
    console.log("size",map.size);
    console.log("delete",map.delete("a"),map);
    console.log("clear",map.clear(),map);

}

  

weakMap

//WeakMap
let weakmap=new WeakMap();

let o={};
weakmap.set(o,123);
console.log(weakmap.get(o));

  

对比

//map、set、object对比
        let item={t:1};
        let map=new Map();
        set =new Set();
        let obj={};

        //增
        map.set("t",1);
        set.add(item);
        obj["t"]=1;
        console.log("map-set-obj",map,set,obj);



        //查
        console.info({
            map_exist:map.has("t"),
            set_exist:set.has(item),
            obj_exist:"t" in obj
        })

        //改
        map.set("t",2);
       // set.forEach(item=>item.t?item.t=2:"");
        item.t=2;
        obj["t"]=2;
        console.log("map-set-obj-change",map,set,obj);

        //删
        map.delete("t");
         set.delete(item);
        delete obj["t"];
         console.log("map-set-obj",map,set,obj);

  

原文地址:https://www.cnblogs.com/karila/p/7867157.html