js实现set
JavaScript 实现 Set 数据结构
在 JavaScript 中,Set 是一种集合数据结构,用于存储唯一值。以下是几种实现 Set 的方法:

使用原生 ES6 Set
ES6 提供了内置的 Set 对象,可以直接使用:

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // 重复值会被忽略
console.log(mySet.has(1)); // true
console.log(mySet.size); // 2
手动实现 Set
如果需要手动实现一个 Set,可以使用对象或数组来模拟:
function CustomSet() {
this.items = {};
}
CustomSet.prototype.add = function(value) {
if (!this.has(value)) {
this.items[value] = value;
return true;
}
return false;
};
CustomSet.prototype.has = function(value) {
return this.items.hasOwnProperty(value);
};
CustomSet.prototype.delete = function(value) {
if (this.has(value)) {
delete this.items[value];
return true;
}
return false;
};
CustomSet.prototype.size = function() {
return Object.keys(this.items).length;
};
// 使用示例
const set = new CustomSet();
set.add(1);
set.add(2);
console.log(set.size()); // 2
使用数组实现 Set
另一种方式是使用数组来存储唯一值:
function ArraySet() {
this.items = [];
}
ArraySet.prototype.add = function(value) {
if (this.items.indexOf(value) === -1) {
this.items.push(value);
return true;
}
return false;
};
ArraySet.prototype.has = function(value) {
return this.items.indexOf(value) !== -1;
};
ArraySet.prototype.delete = function(value) {
const index = this.items.indexOf(value);
if (index !== -1) {
this.items.splice(index, 1);
return true;
}
return false;
};
ArraySet.prototype.size = function() {
return this.items.length;
};
性能比较
- ES6
Set是最高效的实现,底层优化良好。 - 对象实现的
CustomSet适合键为字符串或简单类型的场景。 - 数组实现的
ArraySet在频繁查找或删除时性能较差。
选择哪种实现取决于具体需求。现代开发中推荐直接使用 ES6 Set。





