ES6 set的作用

119 阅读3分钟

ES6 set的作用

ES6 引入了 Set 数据结构,它是一种无序且唯一的值的集合。Set 的主要作用是存储不重复的值,并提供高效的方法来检查某个值是否存在。

以下是 Set 的主要作用和应用场景:

  1. 存储唯一值

Set 的核心特性是它的值总是唯一的,重复的值会被自动忽略。这使得 Set 非常适合用于去重。

示例:

const numbers = [1, 2, 3, 4, 2, 3, 5];
const uniqueNumbers = new Set(numbers);

console.log(uniqueNumbers); // Set { 1, 2, 3, 4, 5 }
  1. 高效的值检查

Set 内部使用哈希表实现,因此检查某个值是否存在于 Set 中的时间复杂度是 O(1),比数组的 includes() 方法(时间复杂度为 O(n))更高效。

示例:

const fruits = new Set(['apple', 'banana', 'orange']);

console.log(fruits.has('banana')); // true
console.log(fruits.has('grape')); // false
  1. 常用操作

Set 提供了一些常用的方法来操作集合:

  • add(value):向 Set 中添加一个值。
  • delete(value):从 Set 中删除一个值。
  • has(value):检查 Set 中是否包含某个值。
  • clear():清空 Set 中的所有值。
  • size:获取 Set 中值的数量。

示例:

const colors = new Set();

colors.add('red');
colors.add('green');
colors.add('blue');
colors.add('red'); // 重复值会被忽略

console.log(colors.size); // 3
console.log(colors.has('green')); // true

colors.delete('blue');
console.log(colors); // Set { 'red', 'green' }

colors.clear();
console.log(colors.size); // 0
  1. 遍历 Set

Set 是可迭代的,可以使用 for...of 循环或 forEach 方法遍历其中的值。

示例:

const letters = new Set(['a', 'b', 'c']);

// 使用 for...of 遍历
for (let letter of letters) {
    console.log(letter); // a, b, c
}

// 使用 forEach 遍历
letters.forEach((value) => {
    console.log(value); // a, b, c
});
  1. 与数组的转换

Set 可以轻松地与数组相互转换,常用于数组去重。

示例:

// 数组去重
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = [...new Set(array)]; // 将 Set 转换为数组

console.log(uniqueArray); // [1, 2, 3, 4, 5]
  1. 存储非原始类型的值

Set 可以存储任何类型的值,包括对象、函数等。需要注意的是,Set 是通过严格相等(===)来判断值是否重复的,因此两个看起来相同的对象会被认为是不同的值。

示例:

const obj1 = { name: 'Alice' };
const obj2 = { name: 'Alice' };

const set = new Set();
set.add(obj1);
set.add(obj2);

console.log(set.size); // 2,因为 obj1 和 obj2 是不同的对象
  1. 应用场景
  • 数组去重:快速去除数组中的重复值。
  • 值的存在性检查:高效地检查某个值是否存在于集合中。
  • 数学集合运算:如并集、交集、差集等。
  • 存储唯一数据:如用户 ID、订单号等需要唯一性的数据。

示例:集合运算

// 并集
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
const union = new Set([...set1, ...set2]);
console.log([...union]); // [1, 2, 3, 4, 5]

// 交集
const intersection = new Set([...set1].filter(x => set2.has(x)));
console.log([...intersection]); // [3]

// 差集
const difference = new Set([...set1].filter(x => !set2.has(x)));
console.log([...difference]); // [1, 2]
  1. WeakSet

ES6 还引入了 WeakSet,它与 Set 类似,但有以下区别:

  • WeakSet 只能存储对象,不能存储原始值。
  • WeakSet 中的对象是弱引用的,不会阻止垃圾回收。
  • WeakSet 不可遍历。

示例:

const weakSet = new WeakSet();
const obj = { name: 'Alice' };

weakSet.add(obj);
console.log(weakSet.has(obj)); // true

// 当 obj 被垃圾回收后,weakSet 中的引用也会自动消失

总结

Set 是 ES6 引入的一种高效的数据结构,用于存储唯一的值。它的主要作用包括去重、高效的值检查、集合运算等。与数组相比,Set 在处理唯一性和存在性检查时更加高效。如果需要存储对象并且不希望阻止垃圾回收,可以使用 WeakSet

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github