js 实现set
使用对象模拟 Set
在 JavaScript 中可以通过对象键的唯一性模拟 Set 功能。创建一个空对象,利用键不重复的特性存储元素。
function CustomSet() {
this.items = {};
}
CustomSet.prototype.add = function(value) {
this.items[value] = true;
};
CustomSet.prototype.has = function(value) {
return this.items.hasOwnProperty(value);
};
CustomSet.prototype.delete = function(value) {
delete this.items[value];
};
CustomSet.prototype.clear = function() {
this.items = {};
};
使用数组实现 Set
通过数组存储元素,在操作时检查元素是否存在。这种方法在性能上不如对象实现,但更直观。

function ArraySet() {
this.items = [];
}
ArraySet.prototype.add = function(value) {
if (!this.items.includes(value)) {
this.items.push(value);
}
};
ArraySet.prototype.has = function(value) {
return this.items.includes(value);
};
ArraySet.prototype.delete = function(value) {
const index = this.items.indexOf(value);
if (index !== -1) {
this.items.splice(index, 1);
}
};
ES6 原生 Set 使用
现代 JavaScript 已内置 Set 对象,直接使用即可获得最佳性能和完善的功能。

const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.has(1); // true
mySet.delete(5);
mySet.size; // 1
实现交集/并集/差集
基于原生 Set 实现集合运算,这些方法可以添加到自定义 Set 实现中。
// 并集
function union(setA, setB) {
return new Set([...setA, ...setB]);
}
// 交集
function intersection(setA, setB) {
return new Set([...setA].filter(x => setB.has(x)));
}
// 差集
function difference(setA, setB) {
return new Set([...setA].filter(x => !setB.has(x)));
}
性能优化建议
对于大规模数据操作,建议使用原生 Set。自定义实现中,对象方式比数组方式性能更好,因为对象键查找时间复杂度是 O(1),而数组查找是 O(n)。
当需要保持插入顺序时,可以结合数组和对象实现,用对象存储存在性,用数组维护顺序。






