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

前端100问笔记 #63

Open
XJIANBIN opened this issue Mar 30, 2021 · 0 comments
Open

前端100问笔记 #63

XJIANBIN opened this issue Mar 30, 2021 · 0 comments

Comments

@XJIANBIN
Copy link
Owner

第 4 题:介绍下 Set、Map、WeakSet 和 WeakMap 的区别?

Set 结构的实例有四个遍历方法,可以用于遍历成员。
Set.prototype.keys():返回键名的遍历器
Set.prototype.values():返回键值的遍历器
Set.prototype.entries():返回键值对的遍历器
Set.prototype.forEach():使用回调函数遍历每个成员

set 结构没有键名,只有键值(或者说相同),
所以遍历方法keys 和values方法的行为完全一致。
set 的遍历顺序就是插入顺序,这个特性可以用来实现需要顺序调用的需求。

扩展运算符内部使用for...of 循环,所以也可以用于set

// 数组去重
let arr = [3,5,2,2,5,5]
let unique = [...new Set(arr)]

let a = new Set([1,2,3])
let b = new Set([4,3,2])

// 并集
let union = new Set([...b, ...b])
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter((x) => {b.has(x)}))
// set {2, 3}

// 差集 (a 相对于b )
let differenct = new Set([...a].filter(x => !b.has(x)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant