推荐答案
Set 是 ES6 引入的一种新的数据结构,它类似于数组,但成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。
本题详细解读
Set 的基本用法
Set 数据结构可以通过 new Set() 来创建,并且可以传入一个数组(或具有 iterable 接口的其他数据结构)作为参数来初始化 Set。
const set = new Set([1, 2, 3, 4, 4]); console.log([...set]); // [1, 2, 3, 4]
在上面的例子中,Set 会自动去除数组中的重复元素。
Set 的属性和方法
Set 实例有以下常用的属性和方法:
- size: 返回 Set 实例的成员总数。
- add(value): 添加某个值,返回 Set 结构本身。
- delete(value): 删除某个值,返回一个布尔值,表示删除是否成功。
- has(value): 返回一个布尔值,表示该值是否为 Set 的成员。
- clear(): 清除所有成员,没有返回值。
const set = new Set(); set.add(1).add(2).add(3); console.log(set.size); // 3 console.log(set.has(2)); // true set.delete(2); console.log(set.has(2)); // false set.clear(); console.log(set.size); // 0
Set 的遍历
Set 结构的实例有四个遍历方法,可以用于遍历成员:
- keys(): 返回键名的遍历器。
- values(): 返回键值的遍历器。
- entries(): 返回键值对的遍历器。
- forEach(): 使用回调函数遍历每个成员。
由于 Set 结构没有键名,只有键值(或者说键名和键值是同一个值),所以 keys() 和 values() 的行为完全一致。
// www.javascriptcn.com code example
const set = new Set(['a', 'b', 'c']);
for (let item of set.keys()) {
console.log(item); // 'a', 'b', 'c'
}
for (let item of set.values()) {
console.log(item); // 'a', 'b', 'c'
}
for (let [key, value] of set.entries()) {
console.log(key, value); // 'a' 'a', 'b' 'b', 'c' 'c'
}
set.forEach((value, key) => {
console.log(key, value); // 'a' 'a', 'b' 'b', 'c' 'c'
});Set 的应用场景
Set 的主要应用场景包括:
- 数组去重:利用 Set 的唯一性,可以轻松实现数组去重。
- 存储不重复的值:在某些场景下,需要存储一组唯一的值,Set 是一个很好的选择。
- 集合运算:可以通过 Set 实现并集、交集、差集等集合运算。
// www.javascriptcn.com code example // 数组去重 const arr = [1, 2, 2, 3, 4, 4, 5]; const uniqueArr = [...new Set(arr)]; console.log(uniqueArr); // [1, 2, 3, 4, 5] // 并集 const set1 = new Set([1, 2, 3]); const set2 = new Set([2, 3, 4]); const union = new Set([...set1, ...set2]); console.log([...union]); // [1, 2, 3, 4] // 交集 const intersection = new Set([...set1].filter(x => set2.has(x))); console.log([...intersection]); // [2, 3] // 差集 const difference = new Set([...set1].filter(x => !set2.has(x))); console.log([...difference]); // [1]
Set 与 WeakSet 的区别
Set 和 WeakSet 都是 ES6 引入的数据结构,但它们有一些重要的区别:
- WeakSet 的成员只能是对象,而不能是其他类型的值。
- WeakSet 中的对象是弱引用,即垃圾回收机制不考虑 WeakSet 对该对象的引用。如果其他对象都不再引用该对象,那么垃圾回收机制会自动回收该对象所占用的内存,不考虑该对象还存在于 WeakSet 之中。
- WeakSet 不可遍历,因此没有
size属性和forEach方法。
const ws = new WeakSet();
const obj = {};
ws.add(obj);
console.log(ws.has(obj)); // true
ws.delete(obj);
console.log(ws.has(obj)); // false总结
Set 是一种非常有用的数据结构,特别适合处理需要唯一值的场景。它的 API 简单易用,且与数组的互操作性很强,能够方便地进行数组去重和集合运算。