**在开发过程中难免会遇到数组去重 或者说 对象中的的键(对象属性)中不能包含键值对 再或者说数组过滤等。那么这时候有些人可能想到循环遍历什么的,可能是能解决但是非常麻烦。为了不麻烦那就让我们麻烦学习一下Set和Map,也是为了以后不麻烦。**
Set常用方法:el.add(value),el.size(),el.delete(value),el.clear(),el.has(value)
1.Set的数组去重
let arr = [1,2,4,5,8,1,7,4,2]
let set = new Set(arr)
arr = Array.from([...set])
console.log(arr)//[1,2,4,5,8,7]
2.Set和另一个Set的交集和并集
交集:
let set = new Set( [1,2,])
let set1 = new Set( [1,2,5,8,7,4])
let arr = [...set1].filter(item => set.has(item))
console.log(arr)//[1, 2]
并集:
let set = new Set( [1,2,])
let set1 = new Set( [1,2,5,8,7,4])
let arr = [...set1].filter(item => !set.has(item))
console.log(arr)//[5, 8, 7, 4]
Map常用方法:el.set(key,value),el.get(value),el.has(value),el.delete(value),el.clear()
1.Map 转为数组
const myMap = new Map()
.set(true, 7)
.set({foo: 3}, ['abc']);
[...myMap]
2.数组 转为 Map
new Map([
[true, 7],
[{foo: 3}, ['abc']]
])
3.Map 转为对象
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
const myMap = new Map()
.set('yes', true)
.set('no', false);
strMapToObj(myMap)
// { yes: true, no: false }
4.对象转为 Map
let obj = {"a":1, "b":2};
let map = new Map(Object.entries(obj));
或者
function objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
}
objToStrMap({yes: true, no: false})
// Map {"yes" => true, "no" => false}
5…Map可以结合Set用于过滤键值对的交集和并集
交集:
let set1 = new Set([1,2])
let set = new Set([
['foo', 1],
['bar', 2],
['br', 3]
]);
console.log(new Map([...set].filter(item => set1.has(item[1])))) //"foo" : 1, "bar" : 2
并集:
```javascript
let set1=new Set([1,2])
let set = new Set([
['foo', 1],
['bar', 2],
['br', 3]
]);
console.log(new Map([...set].filter(item => !set1.has(item[1])))) //"br" : 3
6.Map和过滤器结合使用
let map0 = new Map([
[1,'a'],
[2,'b'],
[3,'c'],
])
let map1 = new Map(
[...map0].filter(([k, v]) => k < 3)
);
// {1 => 'a', 2 => 'b'}
let map2 = new Map(
[...map0].map(([k, v]) => [k * 2, '_' + v])
);
//{2 => '_a', 4 => '_b', 6 => '_c'}