Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 Set 和 Map #23

Open
ChuChencheng opened this issue Jan 10, 2020 · 0 comments
Open

ES6 Set 和 Map #23

ChuChencheng opened this issue Jan 10, 2020 · 0 comments

Comments

@ChuChencheng
Copy link
Owner

Set

定义

不重复值的集合, NaN 在 Set 中是相等的

应用

  1. 去重
[...new Set(array)]

// 或者

Array.from(new Set(array))
  1. 求并集、交集、差集
const a = new Set([1, 2, 3])
const b = new Set([4, 3, 2])

// 并集
const union = new Set([...a, ...b])

// 交集
const intersection = new Set([...a].filter((x) => b.has(x)))

// 差集
const difference = new Set([...a].filter((x) => !b.has(x)))

WeakSet

定义

与 Set 类似, 是不重复值的集合,区别是:

  1. 值只能是对象
  2. 内容是弱引用,内部的对象如果没有被引用,则会被垃圾回收

WeakSet 没有 size 属性,不可遍历

Map

定义

键值对的集合,与对象的区别是,对象只能用字符串作为 key , Map 可以用各种类型的值作为 key 。

内存地址相同的引用类型才视为同一个 key

-0, +0 视为相同 key

NaN 视为相同

构造函数可接受键值对数组或可遍历对象

const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
])

const set = new Set([
  ['foo', 1],
  ['bar', 2]
])
const m1 = new Map(set)

遍历

  • keys()
  • values()
  • entries()
  • forEach()

遍历顺序为插入顺序

转换

  1. Map 转数组
const map = new Map()
map.set(true, 1)
map.set({a: 1}, [666])

[...map]
// [ [ true, 1 ], [ {a: 1}, [666] ] ]
  1. 数组转 Map

即把数组传入 Map 构造函数中,为上述例子的反例

  1. Map 转对象

如果 key 都是字符串,可遍历将 map 转为对象

  1. 对象转 Map

遍历对象,将键值插入 map 中

  1. Map 转 JSON

如果 key 都是字符串,则先转对象,再 JSON.stringify

如果 key 里面有非字符串,则先转数组,再 JSON.stringify

  1. JSON 转 Map

第 5 点的逆操作

WeakMap

类似 Map ,弱引用,没有 size 属性,不可遍历

参考

http://es6.ruanyifeng.com/#docs/set-map

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant