js set 实现
Set 的基本概念
Set 是 ES6 引入的一种新的数据结构,它类似于数组,但成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。
const set = new Set();
创建 Set
可以通过多种方式创建 Set:
// 空 Set
const set1 = new Set();
// 从数组创建
const set2 = new Set([1, 2, 3, 4]);
// 从字符串创建
const set3 = new Set('hello'); // Set {'h', 'e', 'l', 'o'}
Set 的常用方法
Set 提供了一系列方法来操作数据:

const set = new Set();
// 添加元素
set.add(1);
set.add(2).add(3); // 可以链式调用
// 删除元素
set.delete(1); // 返回布尔值,表示是否删除成功
// 检查元素是否存在
set.has(2); // true
// 清空 Set
set.clear();
// 获取元素数量
set.size; // 0
Set 的遍历方法
Set 可以通过多种方式进行遍历:
const set = new Set([1, 2, 3]);
// forEach 方法
set.forEach((value) => console.log(value));
// for...of 循环
for (const item of set) {
console.log(item);
}
// 获取迭代器
const iterator = set.values();
iterator.next(); // {value: 1, done: false}
Set 与数组的转换
Set 和数组可以方便地相互转换:

// 数组转 Set
const arr = [1, 2, 2, 3];
const set = new Set(arr); // Set {1, 2, 3}
// Set 转数组
const uniqueArr = [...set]; // [1, 2, 3]
const uniqueArr2 = Array.from(set); // [1, 2, 3]
Set 的应用场景
Set 常用于需要唯一值的场景:
// 数组去重
const arr = [1, 2, 2, 3, 4, 4];
const uniqueArr = [...new Set(arr)]; // [1, 2, 3, 4]
// 集合运算
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
// 并集
const union = new Set([...setA, ...setB]); // Set {1, 2, 3, 4}
// 交集
const intersection = new Set([...setA].filter(x => setB.has(x))); // Set {2, 3}
// 差集
const difference = new Set([...setA].filter(x => !setB.has(x))); // Set {1}
WeakSet
WeakSet 是 Set 的弱引用版本,只能存储对象引用,且不可遍历:
const ws = new WeakSet();
const obj = {};
ws.add(obj);
ws.has(obj); // true
WeakSet 的主要用途是存储 DOM 节点,当节点被删除时,WeakSet 中的引用会自动被垃圾回收。






