es6 Map与Set
一:map
1.map的基本使用
// map 基本使用 let map = new Map(); map.set('name','WHQ'); map.set('age',24); map.set('未婚',true); console.log(map.get('name')); console.log(map.get('age')); console.log(map.get('未婚'));
2.key不是字符串类型
// 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')))
3.map的迭代
// map迭代 // for .. of for (let [key,value] of map) { console.log(key,value) } // foreach map.forEach(function(value, key, map){ console.log(value,key,map.get(key)) }) // 所有的key for (let key of map.keys()){ console.log(key) } // 所有的值 for (let value of map.values()) { console.log(value) }
4.map的一些操作
// 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对象
1.set对象与map的区别
// set里面的value值是唯一的 // map允许有相同的value值 let myMap = new Map(); myMap.set('no001','张三'); myMap.set('no002','李四'); myMap.set('no003','张三'); console.log(myMap) // set里面的value值是唯一的 let mySet=new Set(); mySet.add('张三') mySet.add('李四') mySet.add('张三') console.log(mySet)
2.set遍历
// set遍历 // for ... of for (let value of mySet.values()) { console.log(value) } // forEach遍历 mySet.forEach(function (value) { console.log(value) })
3.set 转数组
//Set 转数组 let arr3 =[['k1','v1'],[['k2','v2']]]; let set3 = new Set(arr3) console.log(set3) //直接三点运算符,转数组 let arr4 = [...set3] console.log(arr4)
4.数组去重操作
// 数组去重 let arr5 = [1,3,5,3,6]; let set6=new Set(arr5) let arr6=[...set6] 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([...a].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 differenceA3 = new Set([...a3].filter(x => !b3.has(x)));// {1} let differenceB3 = new Set([...b3].filter(x => !a3.has(x))); //{4} console.log('求差集') console.log(differenceA3) console.log(differenceB3)