0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 前端进阶|第三天 集合字典全家桶set&weekset&map&weakmap 思维导图

huaiqiuqiu 2019-09-04 16:25:52 浏览164

1 set 强大数组，可同时存储不同类型的成员，自动去重。

new Set([iterable])

const s = new Set();
[1, 2, 3, 4, 3, 2, 1].forEach(x => s.add(x))

delete(value)：存在即删除集合中value
has(value)：判断集合中是否存在 value
clear()：清空集合

const array = Array.from(set)
const arr = [...set]

let set = new Set([1, 2, 3])
for (let item of set.keys()) {
console.log(item);
}    // 1    2     3
for (let item of set.entries()) {
console.log(item);
}    // [1, 1]    [2, 2]    [3, 3]
set.forEach((value, key) => {
console.log(key + ' : ' + value)
})    // 1 : 1    2 : 2    3 : 3

set 实现并差交

let set1 = new Set([1, 2, 3])
let set2 = new Set([4, 3, 2])

let intersect = new Set([...set1].filter(value => set2.has(value)))
let union = new Set([...set1, ...set2])
let difference = new Set([...set1].filter(value => !set2.has(value)))


2.WeakSet 存储对象

3.Map 字典 存储形式为键值对

const map = new Map();

map.set(['a'], 555);
let obj = ['a'];
let obj2 = ['a'];
map.set(obj, 5556);

console.log(map.get(['a']))//undefined
console.log(map.get(obj)) // 5556
console.log(map.get(obj2)) // undefined


map转换
Map 转 Array

const map = new Map([[1, 1], [2, 2], [3, 3]])
console.log([...map])    // [[1, 1], [2, 2], [3, 3]]

Array 转 Map

const map = new Map([[1, 1], [2, 2], [3, 3]])
console.log(map)

Map 转 Object

function mapToObj(map) {
let obj = Object.create(null)
for (let [key, value] of map) {
obj[key] = value
}
return obj
}
const map = new Map().set('name', 'An').set('des', 'JS')
mapToObj(map)  /

Object 转 Map

function objToMap(obj) {
let map = new Map()
for (let key of Object.keys(obj)) {
map.set(key, obj[key])
}
return map
}

objToMap({'name': 'An', 'des': 'JS'}) // Map {"name" => "An", "des" => "JS"}

Map 转 JSON

function mapToJson(map) {
return JSON.stringify([...map])
}

let map = new Map().set('name', 'An').set('des', 'JS')
mapToJson(map)    // [["name","An"],["des","JS"]]

JSON 转 Map

function jsonToStrMap(jsonStr) {
return objToMap(JSON.parse(jsonStr));
}

jsonToStrMap('{"name": "An", "des": "JS"}') // Map

huaiqiuqiu
+ 关注