ES6 Map&Set

    // map基本使用
    let map=new Map();
    map.set('name','张三');
    map.set('age',11);
    map.set('已婚',false);
    console.log(map.get('name'));
    console.log(map.get('age'));
    console.log(map.get('已婚'));

    // key是对象
    let obj={};
    map.set(obj,'对象');
    console.log(map.get(obj));

    // key是函数
    let func=function(){};
    map.set(func,'函数');
    console.log(map.get(func));

    // key是NaN
    map.set(NaN,'NaN');
    console.log(map.get(NaN));

    console.log(map.get(Number('aaa')));

    // Map迭代
    // for ..of
    for(let[key,value] of map){
        console.log(key,value);
    }

    // forEach
    map.forEach(function(value,key){
        console.log(value,key);
    })

    console.log('所有的key');
    for(let key of map.keys()){
        console.log(key)
    }

    console.log('所有的值');
    for(let value of map.values()){
        console.log(value);
    }

    // Map对象操作
    // Map与Array转换
    // 数组转Map
    let arr=[['k1','v1'],['k2','v2']];
    let map2=new Map(arr);
    console.log(map2);

    // Map转数组
    let arr2=Array.from(map2);
    console.log(arr2);

    // Map合并
    let map3=new Map([...map,...map2]);
    console.log(map3);

    // Set对象
    // Set里的value值是唯一的
    let myMap=new Map();
    myMap.set('no001','张三');
    myMap.set('no002','李四');
    myMap.set('no003','张三');
    console.log(myMap);

    let mySet=new Set();
    mySet.add('张三');
    mySet.add('李四');
    mySet.add('张三');
    console.log(mySet);

    // set遍历
    // for ...of
    for(let value of mySet.values()){
        console.log(value);
    }
    mySet.forEach(function(value){
       console.log(value)
    });

    // Set数组转换
    let arr3=[['k1','v1'],['k2','v2']];
    let set3=new Set(arr3);
    console.log(set3)

    let arr4=[...set3];
    console.log(arr4)

    // 数组去重
    let arr5=[1,3,5,3,6];
    let set6=new Set(arr5);
    let arr6=[...set6];
    console.log('数组去重')
    console.log(arr6)

    // 求并集
    let a = new Set([1, 2, 3]);
    let b = new Set([4, 3, 2]);
    let union = new Set([...a, ...b]); // {1, 2, 3, 4}
    console.log('求并集')
    console.log(union)

    // 求交集
    let a2 = new Set([1, 2, 3]);
    let b2 = new Set([4, 3, 2]);
    let intersect = new Set([...a2].filter(x => b2.has(x))); // {2, 3}
    console.log('求交集')
    console.log(intersect)

    // 求差集
    let a3 = new Set([1, 2, 3]);
    let b3 = new Set([4, 3, 2]);
    let difference = new Set([...a3].filter(x => !b3.has(x))); // {1}
    console.log('求差集')
    console.log(difference)

 

猜你喜欢

转载自www.cnblogs.com/zsh-blogs/p/12963831.html