js set 实现
使用 Set 实现去重
Set 是 ES6 引入的一种新的数据结构,类似于数组,但成员的值都是唯一的,没有重复的值。可以利用 Set 这一特性轻松实现数组去重。
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
使用 Set 进行集合运算
Set 数据结构支持多种集合运算,如并集、交集、差集等。
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
// 并集
const union = new Set([...setA, ...setB]);
// 交集
const intersection = new Set([...setA].filter(x => setB.has(x)));
// 差集
const difference = new Set([...setA].filter(x => !setB.has(x)));
使用 Set 存储唯一值
Set 可以确保存储的值都是唯一的,即使添加重复值也不会生效。

const set = new Set();
set.add(1);
set.add(2);
set.add(1); // 不会生效
console.log(set.size); // 2
Set 的常用方法
Set 提供了一系列方法用于操作和查询集合。
const set = new Set([1, 2, 3]);
// 添加元素
set.add(4);
// 删除元素
set.delete(1);
// 检查元素是否存在
console.log(set.has(2)); // true
// 清空集合
set.clear();
// 获取集合大小
console.log(set.size);
遍历 Set
Set 可以使用多种方式进行遍历。

const set = new Set([1, 2, 3]);
// 使用 for...of
for (const item of set) {
console.log(item);
}
// 使用 forEach
set.forEach(item => {
console.log(item);
});
Set 与数组的转换
Set 和数组之间可以方便地进行转换。
// 数组转 Set
const arr = [1, 2, 3];
const set = new Set(arr);
// Set 转数组
const newArr = [...set];
const newArr2 = Array.from(set);
使用 Set 进行高性能查找
Set 的 has 方法在查找元素时比数组的 includes 方法更高效,尤其是在数据量较大时。
const set = new Set([1, 2, 3, 4, 5]);
console.log(set.has(3)); // true
注意事项
Set 中的元素是通过 === 严格相等比较的,NaN 在 Set 中被认为是相等的,而对象和数组等引用类型需要特别注意。
const set = new Set();
set.add(NaN);
set.add(NaN);
console.log(set.size); // 1
const obj1 = { a: 1 };
const obj2 = { a: 1 };
set.add(obj1);
set.add(obj2);
console.log(set.size); // 3






