跳转到内容

JavaScript Set

来自代码酷


JavaScript Set 是 ES6(ECMAScript 2015)引入的一种新的数据结构,用于存储唯一值的集合。与数组不同,Set 中的每个值必须是唯一的,且不会存储重复项。Set 提供了高效的方法来检查、添加和删除元素,适用于需要去重或快速查找的场景。

基本介绍[编辑 | 编辑源代码]

Set 是一种有序集合,其元素可以是任意类型(原始值或对象引用)。Set 的主要特点包括:

  • 唯一性:Set 中的每个值只能出现一次。
  • 迭代顺序:Set 按照插入顺序迭代元素。
  • 高效操作:Set 的查找、插入和删除操作的时间复杂度接近 O(1)。

Set 的构造函数接受一个可迭代对象(如数组)作为参数,并自动去除重复项。

创建 Set[编辑 | 编辑源代码]

可以使用 `new Set()` 构造函数创建一个空的 Set,或者传入一个可迭代对象来初始化 Set。

// 创建一个空的 Set
const emptySet = new Set();

// 从数组创建 Set(自动去重)
const numbers = new Set([1, 2, 2, 3, 4, 4]);
console.log(numbers); // 输出: Set {1, 2, 3, 4}

// 从字符串创建 Set(每个字符唯一)
const chars = new Set("hello");
console.log(chars); // 输出: Set {"h", "e", "l", "o"}

Set 的常用方法[编辑 | 编辑源代码]

Set 提供了多种方法来操作集合:

添加元素[编辑 | 编辑源代码]

使用 `add()` 方法向 Set 中添加元素。如果元素已存在,则不会重复添加。

const fruits = new Set();
fruits.add("apple");
fruits.add("banana");
fruits.add("apple"); // 重复添加,不会生效
console.log(fruits); // 输出: Set {"apple", "banana"}

删除元素[编辑 | 编辑源代码]

使用 `delete()` 方法从 Set 中移除元素。如果元素存在并成功删除,返回 `true`;否则返回 `false`。

const colors = new Set(["red", "green", "blue"]);
colors.delete("green"); // 返回 true
colors.delete("yellow"); // 返回 false
console.log(colors); // 输出: Set {"red", "blue"}

检查元素是否存在[编辑 | 编辑源代码]

使用 `has()` 方法检查 Set 中是否包含某个元素。

const animals = new Set(["cat", "dog", "bird"]);
console.log(animals.has("dog")); // 输出: true
console.log(animals.has("fish")); // 输出: false

清空 Set[编辑 | 编辑源代码]

使用 `clear()` 方法移除 Set 中的所有元素。

const letters = new Set(["a", "b", "c"]);
letters.clear();
console.log(letters); // 输出: Set {}

获取 Set 的大小[编辑 | 编辑源代码]

使用 `size` 属性获取 Set 中元素的数量。

const primes = new Set([2, 3, 5, 7, 11]);
console.log(primes.size); // 输出: 5

迭代 Set[编辑 | 编辑源代码]

Set 是可迭代的,可以通过以下方式遍历其元素:

使用 `for...of` 循环[编辑 | 编辑源代码]

const languages = new Set(["JavaScript", "Python", "Java"]);
for (const lang of languages) {
    console.log(lang);
}
// 输出:
// JavaScript
// Python
// Java

使用 `forEach()` 方法[编辑 | 编辑源代码]

const cities = new Set(["Tokyo", "New York", "London"]);
cities.forEach((city) => {
    console.log(city);
});
// 输出:
// Tokyo
// New York
// London

Set 与数组的转换[编辑 | 编辑源代码]

Set 可以与数组互相转换,常用于去重操作。

数组转 Set[编辑 | 编辑源代码]

const array = [1, 2, 2, 3, 3, 4];
const uniqueSet = new Set(array);
console.log(uniqueSet); // 输出: Set {1, 2, 3, 4}

Set 转数组[编辑 | 编辑源代码]

const set = new Set(["a", "b", "c"]);
const arrayFromSet = Array.from(set); // 或 [...set]
console.log(arrayFromSet); // 输出: ["a", "b", "c"]

实际应用案例[编辑 | 编辑源代码]

Set 在实际开发中有多种用途,以下是几个常见场景:

数组去重[编辑 | 编辑源代码]

const duplicates = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(duplicates)];
console.log(unique); // 输出: [1, 2, 3, 4, 5]

检查列表中的唯一值[编辑 | 编辑源代码]

function hasDuplicates(array) {
    return array.length !== new Set(array).size;
}
console.log(hasDuplicates([1, 2, 3])); // 输出: false
console.log(hasDuplicates([1, 2, 2])); // 输出: true

集合运算[编辑 | 编辑源代码]

Set 可以模拟数学中的集合运算,如并集、交集和差集。

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

// 并集
const union = new Set([...setA, ...setB]);
console.log(union); // 输出: Set {1, 2, 3, 4}

// 交集
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // 输出: Set {2, 3}

// 差集 (A - B)
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // 输出: Set {1}

性能考虑[编辑 | 编辑源代码]

Set 的查找和插入操作通常比数组更高效:

  • `Set.has()` 的时间复杂度为 O(1),而 `Array.includes()` 为 O(n)。
  • Set 自动去重,无需手动处理重复值。

总结[编辑 | 编辑源代码]

JavaScript Set 是一种强大的数据结构,适用于存储唯一值和高效查找。它与数组互补,特别适合去重、集合运算和快速成员检查等场景。通过掌握 Set 的方法和特性,开发者可以编写更简洁、高效的代码。

参见[编辑 | 编辑源代码]