js 实现set
使用对象模拟 Set
在 JavaScript 中,可以通过对象来模拟 Set 的功能。对象的键是唯一的,可以用来存储 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 = {};
};
CustomSet.prototype.size = function() {
return Object.keys(this.items).length;
};
使用数组实现 Set
另一种方法是使用数组来存储元素,并通过数组的方法来实现 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);
return true;
}
return false;
};
ArraySet.prototype.clear = function() {
this.items = [];
};
ArraySet.prototype.size = function() {
return this.items.length;
};
ES6 原生 Set
现代 JavaScript 已经内置了 Set 对象,可以直接使用。

const set = new Set();
set.add(1);
set.add(2);
set.add(1); // 重复值不会被添加
console.log(set.has(1)); // true
console.log(set.size); // 2
set.delete(1);
console.log(set.has(1)); // false
set.clear();
console.log(set.size); // 0
自定义 Set 的迭代功能
如果需要自定义 Set 的迭代功能,可以实现 Symbol.iterator 方法。
CustomSet.prototype[Symbol.iterator] = function*() {
for (const key in this.items) {
yield key;
}
};
const customSet = new CustomSet();
customSet.add('a');
customSet.add('b');
for (const item of customSet) {
console.log(item); // 'a', 'b'
}
实现 Set 的并集、交集和差集
可以扩展 Set 的功能,实现集合的常见操作。
CustomSet.prototype.union = function(otherSet) {
const unionSet = new CustomSet();
for (const item in this.items) {
unionSet.add(item);
}
for (const item in otherSet.items) {
unionSet.add(item);
}
return unionSet;
};
CustomSet.prototype.intersection = function(otherSet) {
const intersectionSet = new CustomSet();
for (const item in this.items) {
if (otherSet.has(item)) {
intersectionSet.add(item);
}
}
return intersectionSet;
};
CustomSet.prototype.difference = function(otherSet) {
const differenceSet = new CustomSet();
for (const item in this.items) {
if (!otherSet.has(item)) {
differenceSet.add(item);
}
}
return differenceSet;
};






