es6语法之map,set
1.map
let map = new Map() //创建一个map对象
map.set('aa', 123)
console.log(map.get('aa'), 'jwq')//显示结果是123,'jwq'
2.map与array的转换
- 二维数组转换为Map对象
let jwqArray = [["jwq", "value1"], ["zhn", "value2"]];
let myMap = new Map(jwqArray);
console.log(typeof myMap,myMap,'jwq')
-
Map对象转换为二维数组(使用Array.from)
let jwqArray = [["jwq", "value1"], ["zhn", "value2"]]; let myMap = new Map(jwqArray); let outArray = Array.from(myMap) console.log(typeof outArray,outArray,'jwq')
-
map的克隆
let myMap1 = new Map([["jwq", "value1"], ["zhn", "value2"]]); let myMap2 = new Map(myMap1); myMap1.set('jwq', 'value3') console.log(myMap1, 'myMap1', myMap2, 'myMap2') //可以从截图中看出来,克隆出来的myMap2与原来的myMap1没有任何的关系,要不然我们的myMap2也会变成myMap1的样子,可以认为是深层次克隆,深拷贝
-
map的合并
let first = new Map([[1, 'one'], [2, 'two'], [3, 'three'],]); let second = new Map([[1, 'four'], [2, 'fiv']]); let jwq = new Map([...first, ...second]) console.log(jwq, 'jwq') //看下面的截图应该知道1对应的变成了four而2对应的变为fiv,是因为后面的值把前面的值覆盖了,所以map的合并,是后面的值会覆盖前面的值
3.set对象
-
数组去重
let jwq = new Set([1, 2, 3, 4, 4]); console.log([...jwq], 'jwq') //有时候我们就需要数组去重,我们可以先创建set对象,在转换为array //let myArray = [...jwq]
-
并集
let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); let jwq = new Set([...a, ...b]); console.log(jwq, 'jwq')
-
交集
let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); let jwq = new Set([...a].filter(x => b.has(x))); console.log(jwq, 'jwq') //他们两个的交集是23
-
差集
let a = new Set([1, 2, 3]); let b = new Set([3, 4, 5]); let jwq = new Set([...a].filter(x => !b.has(x))); console.log(jwq, 'jwq') //a和b的差集应该是1245,那么相对于a,他的差集就是12