js实现集合
集合的基本概念
在JavaScript中,集合(Set)是一种存储唯一值的数据结构,不允许重复元素。ES6引入了原生Set对象,但也可以手动实现类似功能。
使用原生Set对象
ES6的Set对象提供集合功能:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // 重复值不会被添加
console.log(mySet.size); // 2
console.log(mySet.has(1)); // true
mySet.delete(2);
手动实现集合类
可以创建一个自定义集合类:
class MySet {
constructor() {
this.items = {};
}
has(value) {
return this.items.hasOwnProperty(value);
}
add(value) {
if (!this.has(value)) {
this.items[value] = value;
return true;
}
return false;
}
delete(value) {
if (this.has(value)) {
delete this.items[value];
return true;
}
return false;
}
size() {
return Object.keys(this.items).length;
}
values() {
return Object.values(this.items);
}
}
集合操作
实现常见的集合操作:
// 并集
function union(setA, setB) {
const unionSet = new Set();
setA.forEach(value => unionSet.add(value));
setB.forEach(value => unionSet.add(value));
return unionSet;
}
// 交集
function intersection(setA, setB) {
const intersectionSet = new Set();
setA.forEach(value => {
if (setB.has(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
// 差集
function difference(setA, setB) {
const differenceSet = new Set();
setA.forEach(value => {
if (!setB.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
}
集合与数组转换
集合与数组之间可以相互转换:
// 数组转集合
const arr = [1, 2, 3, 3];
const setFromArr = new Set(arr); // {1, 2, 3}
// 集合转数组
const arrFromSet = [...setFromArr]; // [1, 2, 3]
集合的迭代
可以使用各种方式迭代集合:
const mySet = new Set([1, 2, 3]);
// for...of循环
for (let item of mySet) {
console.log(item);
}
// forEach方法
mySet.forEach(value => {
console.log(value);
});
WeakSet
对于对象集合,可以使用WeakSet,它只存储对象引用且是弱引用:

const weakSet = new WeakSet();
const obj = {};
weakSet.add(obj);
console.log(weakSet.has(obj)); // true






