js 实现集合
实现集合的基本方法
在JavaScript中,集合(Set)是一种无序且元素唯一的数据结构。可以使用原生Set对象或手动实现类似功能。
使用原生Set对象:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // 重复元素不会被添加
console.log(mySet.size); // 输出2
手动实现集合类:
class MySet {
constructor() {
this.items = {};
}
has(element) {
return Object.prototype.hasOwnProperty.call(this.items, element);
}
add(element) {
if (!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
delete(element) {
if (this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
size() {
return Object.keys(this.items).length;
}
}
集合操作的方法
实现并集(union)操作:
union(otherSet) {
const unionSet = new MySet();
Object.values(this.items).forEach(value => unionSet.add(value));
Object.values(otherSet.items).forEach(value => unionSet.add(value));
return unionSet;
}
实现交集(intersection)操作:
intersection(otherSet) {
const intersectionSet = new MySet();
Object.values(this.items).forEach(value => {
if (otherSet.has(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
实现差集(difference)操作:
difference(otherSet) {
const differenceSet = new MySet();
Object.values(this.items).forEach(value => {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
}
集合的扩展功能
实现子集判断:
isSubsetOf(otherSet) {
return Object.values(this.items).every(value =>
otherSet.has(value)
);
}
实现集合转数组:
toArray() {
return Object.values(this.items);
}
实现清空集合:
clear() {
this.items = {};
}
ES6 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进行数组去重:

const arr = [1, 2, 2, 3, 4, 4];
const uniqueArr = [...new Set(arr)];






