集合

集合是什么?

一种 无序且唯一 的数据结构
ES6中有集合,名为Set
集合的常用操作:数组去重,判断某元素是否在集合中,求交集

// 去重
const arr = [1, 1, 2, 2]
const set = new Set(arr) // { 1, 2 }
const arr2 = [...set]

// 判断元素是否在集合中
const has = set.has(3)

// 求交集
const set2 = new Set([2, 3])
const set3 = new Set([...set].filter(item => set2.has(item))) //{ 2 }
posted @ 2022-05-11 12:06  见信  阅读(29)  评论(0)    收藏  举报