js实现的集合
JavaScript 中的集合实现
JavaScript 提供了多种方式来实现集合(Set)数据结构,以下是常见的几种方法:
使用原生 Set 对象
ES6 引入了原生的 Set 对象,它允许存储任何类型的唯一值:
const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add('some text');
console.log(mySet.has(1)); // true
console.log(mySet.size); // 3
mySet.delete(5); // 移除5
Set 对象自动处理唯一性,重复添加的值会被忽略。
使用对象模拟集合
在 ES6 之前,可以使用普通对象来模拟集合:
const set = {};
set['key1'] = true;
set['key2'] = true;
if (set['key1']) {
console.log('key1 exists');
}
delete set['key1'];
这种方法只能使用字符串作为键,且无法直接存储对象引用。
实现完整集合功能
如需完整集合功能(并集、交集等),可以扩展 Set 类:
class EnhancedSet extends Set {
union(otherSet) {
return new EnhancedSet([...this, ...otherSet]);
}
intersection(otherSet) {
return new EnhancedSet([...this].filter(x => otherSet.has(x)));
}
difference(otherSet) {
return new EnhancedSet([...this].filter(x => !otherSet.has(x)));
}
}
使用数组实现集合
虽然效率较低,但可以用数组模拟集合:
const set = [];
function add(item) {
if (!set.includes(item)) {
set.push(item);
}
}
function has(item) {
return set.includes(item);
}
function remove(item) {
const index = set.indexOf(item);
if (index > -1) {
set.splice(index, 1);
}
}
性能考虑
- 原生 Set 对象在查找、添加和删除操作上都是 O(1) 时间复杂度
- 数组实现的集合在查找操作上是 O(n) 时间复杂度
- 对象实现的集合在查找操作上是 O(1),但仅限于字符串键
集合操作示例
实现常见集合操作:
// 并集
const union = (setA, setB) => new Set([...setA, ...setB]);
// 交集
const intersection = (setA, setB) => new Set([...setA].filter(x => setB.has(x)));
// 差集
const difference = (setA, setB) => new Set([...setA].filter(x => !setB.has(x)));
对于大多数应用场景,推荐使用原生 Set 对象,它提供了最佳性能和最简洁的语法。需要额外功能时,可以扩展原生 Set 或使用第三方库如 lodash 的集合操作方法。







