js 实现集合
实现集合的基本方法
在 JavaScript 中,集合(Set)是一种存储唯一值的数据结构。可以使用多种方式实现集合功能。
使用 ES6 的 Set 类是最简单的方式:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重复值会被忽略
console.log(mySet.has(1)); // true
mySet.delete(1);
使用对象模拟集合
在 ES6 之前,可以用对象模拟集合:
function Set() {
this.items = {};
}
Set.prototype.add = function(value) {
this.items[value] = true;
};
Set.prototype.has = function(value) {
return this.items.hasOwnProperty(value);
};
Set.prototype.delete = function(value) {
delete this.items[value];
};
Set.prototype.size = function() {
return Object.keys(this.items).length;
};
集合操作实现
实现集合的并集、交集和差集:
// 并集
Set.prototype.union = function(otherSet) {
const unionSet = new Set();
Object.keys(this.items).forEach(value => unionSet.add(value));
Object.keys(otherSet.items).forEach(value => unionSet.add(value));
return unionSet;
};
// 交集
Set.prototype.intersection = function(otherSet) {
const intersectionSet = new Set();
Object.keys(this.items).forEach(value => {
if(otherSet.has(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
};
// 差集
Set.prototype.difference = function(otherSet) {
const differenceSet = new Set();
Object.keys(this.items).forEach(value => {
if(!otherSet.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
};
使用数组实现集合
另一种实现方式是使用数组:
class ArraySet {
constructor() {
this.items = [];
}
add(value) {
if(!this.has(value)) {
this.items.push(value);
}
}
has(value) {
return this.items.includes(value);
}
delete(value) {
const index = this.items.indexOf(value);
if(index !== -1) {
this.items.splice(index, 1);
}
}
get size() {
return this.items.length;
}
}
集合的性能考虑
对于大型集合,基于对象的实现通常比数组实现性能更好,因为对象使用哈希表结构,查找操作的时间复杂度接近 O(1),而数组需要线性查找。

ES6 的 Set 类已经优化了性能,建议优先使用原生 Set 而不是自定义实现,除非有特殊需求。






