js实现set函数
实现 Set 函数
在 JavaScript 中,Set 是一种内置数据结构,用于存储唯一值。如果需要手动实现类似功能,可以通过对象或数组模拟其行为。

基于对象的实现
利用对象的键唯一性模拟 Set 的行为:

function CustomSet() {
this.items = {};
}
CustomSet.prototype.add = function(value) {
this.items[value] = true;
return this;
};
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.clear = function() {
this.items = {};
};
CustomSet.prototype.size = function() {
return Object.keys(this.items).length;
};
CustomSet.prototype.values = function() {
return Object.keys(this.items);
};
基于数组的实现
通过数组存储值,并确保唯一性:
function ArraySet() {
this.items = [];
}
ArraySet.prototype.add = function(value) {
if (!this.items.includes(value)) {
this.items.push(value);
}
return this;
};
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);
return true;
}
return false;
};
ArraySet.prototype.clear = function() {
this.items = [];
};
ArraySet.prototype.size = function() {
return this.items.length;
};
ArraySet.prototype.values = function() {
return [...this.items];
};
ES6 Class 实现
使用 ES6 的 class 语法实现 Set:
class MySet {
constructor() {
this.collection = [];
}
has(element) {
return this.collection.indexOf(element) !== -1;
}
add(element) {
if (!this.has(element)) {
this.collection.push(element);
return true;
}
return false;
}
delete(element) {
if (this.has(element)) {
const index = this.collection.indexOf(element);
this.collection.splice(index, 1);
return true;
}
return false;
}
size() {
return this.collection.length;
}
values() {
return this.collection;
}
}
注意事项
- 对象实现的
Set会将所有键转换为字符串,可能导致类型混淆。 - 数组实现的
Set在大型数据集上性能较低,因为需要遍历检查唯一性。 - 实际开发中应优先使用原生
Set,性能更高且功能完善。






