js实现set
使用原生 JavaScript 实现 Set 功能
JavaScript 的 Set 是一种集合数据结构,用于存储唯一值。以下是一个简单的原生 JavaScript 实现:
class MySet {
constructor() {
this.items = {};
}
has(element) {
return Object.prototype.hasOwnProperty.call(this.items, element);
}
add(element) {
if (!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
delete(element) {
if (this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
clear() {
this.items = {};
}
size() {
return Object.keys(this.items).length;
}
values() {
return Object.values(this.items);
}
}
使用对象存储集合元素
上述实现使用对象来存储集合元素,利用对象的键唯一性来保证集合元素的唯一性。has 方法检查元素是否存在,add 方法添加新元素,delete 方法移除元素。

处理不同类型的值
JavaScript 的对象键会自动转换为字符串,这可能导致一些问题。例如,数字 1 和字符串 '1' 会被视为相同的键。为了解决这个问题,可以改进实现:

class MySet {
constructor() {
this.items = [];
}
has(element) {
return this.items.includes(element);
}
add(element) {
if (!this.has(element)) {
this.items.push(element);
return true;
}
return false;
}
delete(element) {
if (this.has(element)) {
this.items.splice(this.items.indexOf(element), 1);
return true;
}
return false;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
values() {
return [...this.items];
}
}
实现集合运算
集合常见的运算包括并集、交集、差集和子集。以下是这些运算的实现:
union(otherSet) {
const unionSet = new MySet();
this.values().forEach(value => unionSet.add(value));
otherSet.values().forEach(value => unionSet.add(value));
return unionSet;
}
intersection(otherSet) {
const intersectionSet = new MySet();
this.values().forEach(value => {
if (otherSet.has(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
difference(otherSet) {
const differenceSet = new MySet();
this.values().forEach(value => {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
}
isSubsetOf(otherSet) {
return this.values().every(value => otherSet.has(value));
}
使用 ES6 的 Set
现代 JavaScript 已经内置了 Set 类,可以直接使用:
const set = new Set();
set.add(1);
set.add(2);
set.add(1); // 不会重复添加
console.log(set.size); // 2
console.log(set.has(1)); // true
set.delete(1);
console.log(set.has(1)); // false
性能考虑
原生实现的 Set 性能可能不如内置的 Set,特别是在处理大量数据时。内置 Set 经过优化,通常具有更好的性能。






