1. Set
Set有点类似数组,但是Set和数组最大的不同在于Set中不能存在相同的元素。
new Set([1,2,3,4,1,2,3,4]); // { 1, 2, 3, 4 }
其次,Set的内置函数也没有数组那么丰富。主要有:add()、has()、delete()、clear()、keys()、values()、entries()、forEach()
// 1、初始化 Set
const set = new Set();
// 2、添加值
set.add(1);
set.add(2);
set.add(3).add(4); // Set(4) {1, 2, 3, 4}
// 3、删除值
set.delete(1); // true
console.log(set); // Set(3) {2, 3, 4}
// 4、查找值
set.has(3); // true
set.has(1); // false
// 5、清空 Set
set.clear();
console.log(set); // Set(0) {}
// 6、遍历 Set
set = new Set([1,2,3,4]);
for (const key of set.keys()) {
console.log(key);
}
/*
* 1
* 2
* 3
* 4
*/
for (const value of set.values()) {
console.log(value);
}
/*
* 1
* 2
* 3
* 4
*/
for (const item of set.entries()) {
console.log(item);
}
/*
* [1,1]
* [2,2]
* [3,3]
* [4,4]
*/
// 注意:values()为默认迭代方法,keys()为values()方法的别名
set.values === set[Symbol.iterator] === set.keys
// 因此可以直接这么用
for (const val of set) {
console.log(val);
}
/*
* 1
* 2
* 3
* 4
*/
// 也可以使用forEach()方法遍历,使用方法和数组的forEach()相同
set.forEach((key, value) => {
console.log(key, value);
});
/*
* 1 1
* 2 2
* 3 3
* 4 4
*/
除上面的方法外,Set还有一个实例属性size。表示Set实例的长度。
const set = new Set([1,2,3,4]);
set.size // 4
Set可以使用解构
const set = new Set();
set.add(1).add(2).add(3); // Set(3) { 1, 2, 3 }
[...set] // [1,2,3]
利用Set内不能存在相同元素的特性,我们可以用Set来做数组的去重。
let arr = [1,2,3,4,2,3,4,1,2,5];
// 使用 Set 去重
arr = [...new Set(arr)]; // [1, 2, 3, 4, 5]
使用Set实现并集、交集、差集、对称差集
// 实现并集
function union(first, ...others) {
const unionSet = new Set(first);
for (const set of others) {
for (const setValue of set) {
unionSet.add(setValue);
}
}
return unionSet;
}
// 实现交集
function intersection(first, ...others) {
const intersectionSet = new Set(first);
for (const value of intersectionSet) {
for (const set of others) {
if (!set.has(value)) {
intersectionSet.delete(value);
}
}
}
return intersectionSet;
}
// 实现两个集合的差集
function difference(a, b) {
const set = new Set(a);
for (const bValue of b) {
if(set.has(bValue)) {
set.delete(bValue);
}
}
return set;
}
// 实现两个集合的对称差集
function symmetricDifference(a, b) {
return difference(union(a, b), intersection(a, b));
}
2. WeakSet
WeakSet和WeakMap类似,WeakSet的元素只能是对象类型的。只有以下的方法:
const ws = new WeakSet();
const obj = {
o: { msg: 'message' }
};
// 1. 添加元素
ws.add(obj.o);
// 2. 查找元素
ws.has(obj.o);
// 3. 删除元素
ws.delete(obj.o);
和WeakMap一样,WeakSet也不能遍历,是一种弱映射,里面的元素不会被计入垃圾回收机制,只要元素引用清空了对应WeakSet也会清空。
WeakSet的应用没有WeakMap那样广泛,但是它可以用来给DOM元素做一个标记。例如:我们需要给某个元素设置禁用的标记。
const btn = document.querySelector('button');
btn.setAttribute('disabled', true);
const set = new WeakSet();
set.add(btn);
// 通过查找 set 中是否存在对应元素来判断这个元素是否被禁用了
set.has(btn);
这样的好处是如果DOM节点删除了,那么set内对应的元素也会被垃圾回收机制回收。避免了内存占用。
本文详细介绍了JavaScript中的Set和WeakSet数据结构。Set用于存储不重复的元素,提供了add、has、delete等操作,并可用于数组去重、实现并集、交集、差集和对称差集。WeakSet则只接受对象作为元素,无法遍历,其元素不会阻止垃圾回收,适合用于对DOM元素的标记,以避免内存占用。
855

被折叠的 条评论
为什么被折叠?



