js实现的集合
JavaScript 集合的实现方法
JavaScript 提供了多种方式来实现集合(Set)数据结构,以下是几种常见的方法:
使用 ES6 的 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
使用数组模拟集合
在没有 Set 支持的旧环境中,可以使用数组来模拟集合:
function Set() {
this.values = [];
this.add = function(value) {
if (this.values.indexOf(value) === -1) {
this.values.push(value);
}
};
this.has = function(value) {
return this.values.indexOf(value) !== -1;
};
}
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
使用对象模拟集合
另一种方法是利用对象的键唯一性来模拟集合:
function Set() {
this.values = {};
this.add = function(value) {
this.values[value] = true;
};
this.has = function(value) {
return this.values[value] === true;
};
}
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
集合操作实现
可以扩展集合的基本功能,实现并集、交集、差集等操作:
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;
}
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(otherSet) {
const intersectionSet = new MySet();
Object.values(this.items).forEach(value => {
if (otherSet.has(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
}
性能考虑
对于大型数据集,Set 对象的性能通常优于数组实现,因为 Set 的查找操作时间复杂度为 O(1),而数组的 indexOf 方法为 O(n)。

// Set 性能示例
const largeSet = new Set();
for (let i = 0; i < 1000000; i++) {
largeSet.add(i);
}
console.time('Set查找');
largeSet.has(999999);
console.timeEnd('Set查找');
// 数组性能示例
const largeArray = [];
for (let i = 0; i < 1000000; i++) {
if (largeArray.indexOf(i) === -1) {
largeArray.push(i);
}
}
console.time('数组查找');
largeArray.indexOf(999999);
console.timeEnd('数组查找');
以上方法提供了在 JavaScript 中实现集合的不同方式,可以根据具体需求和环境选择最适合的实现。






