ZetCode

JavaScript Set 关键字

最后修改于 2025 年 4 月 16 日

在本文中,我们将展示如何使用 JavaScript 中的 Set 对象来处理唯一值的集合。

Set 对象

Set 对象是一个唯一值的集合。它可以存储任何类型的值,无论是基本类型值还是对象引用。每个值在 Set 中只能出现一次。

Sets 类似于数组,但它们不允许重复值。它们提供了添加、删除和检查元素存在的方法。 Sets 保持元素的插入顺序。

当您需要维护唯一项目的集合时,Sets 很有用。与数组相比,它们在某些操作中提供了更好的性能。

创建集合

以下示例演示了如何在 JavaScript 中创建一个 Set。

main.js
const mySet = new Set();

mySet.add(1);
mySet.add(5);
mySet.add('text');
mySet.add({name: 'John'});

console.log(mySet);

我们使用 new Set() 构造函数创建一个新的 Set。我们使用 add() 方法向 Set 添加各种类型的值。 Set 可以包含数字、字符串和对象。

$ node main.js
Set { 1, 5, 'text', { name: 'John' } }

从数组创建 Set

我们可以从一个数组创建一个 Set,它会自动删除重复项。

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

console.log(uniqueNumbers);
console.log([...uniqueNumbers]);

此示例展示了如何从包含重复值的数组创建 Set。Set 会自动删除重复项。我们使用扩展运算符将 Set 转换回数组。

$ node main.js
Set { 1, 2, 3, 4, 5 }
[ 1, 2, 3, 4, 5 ]

检查 Set 的大小和存在性

Sets 提供了检查其大小以及它们是否包含值的方法。

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

console.log(fruits.size);
console.log(fruits.has('apple'));
console.log(fruits.has('grape'));

size 属性返回 Set 中元素的数量。has() 方法检查 Set 中是否存在某个值。这两个操作在 Sets 中都非常有效。

$ node main.js
3
true
false

从 Set 中删除元素

Sets 提供了删除单个元素或清除所有元素的方法。

main.js
const colors = new Set(['red', 'green', 'blue']);

colors.delete('green');
console.log(colors);

colors.clear();
console.log(colors);

delete() 方法从 Set 中删除特定元素。clear() 方法从 Set 中删除所有元素。这两种方法都会就地修改 Set。

$ node main.js
Set { 'red', 'blue' }
Set {}

遍历 Set

Sets 可以使用各种方法进行迭代,类似于数组。

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

// Using for...of
for (const letter of letters) {
    console.log(letter);
}

// Using forEach
letters.forEach(letter => {
    console.log(letter);
});

Sets 保持插入顺序,因此迭代遵循添加元素的顺序。我们可以使用 for...offorEach 来遍历 Set。 Sets 是可迭代的对象。

$ node main.js
a
b
c
a
b
c

Set 运算:并集、交集、差集

我们可以执行常见的 Set 运算,例如并集、交集和差集。

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

// Union
const union = new Set([...setA, ...setB]);
console.log(union);

// Intersection
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection);

// Difference
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference);

此示例演示了基本的 Set 运算。并集将两个集合的元素组合在一起。交集找到公共元素。差集找到 setA 中但不在 setB 中的元素。

$ node main.js
Set { 1, 2, 3, 4 }
Set { 2, 3 }
Set { 1 }

实际用例:跟踪唯一访问者

这是一个使用 Set 跟踪唯一网站访问者的实际例子。

main.js
const visitors = new Set();

function addVisitor(id) {
    visitors.add(id);
    console.log(`Total unique visitors: ${visitors.size}`);
}

addVisitor('user1');
addVisitor('user2');
addVisitor('user1'); // Duplicate
addVisitor('user3');

console.log('All visitors:', [...visitors]);

此代码使用 Set 来跟踪唯一的访问者 ID。重复的 ID 会被自动忽略。 size 属性给出了唯一访问者的计数。

$ node main.js
Total unique visitors: 1
Total unique visitors: 2
Total unique visitors: 2
Total unique visitors: 3
All visitors: [ 'user1', 'user2', 'user3' ]

来源

Set - 语言参考

在本文中,我们演示了如何使用 Set 对象来处理 JavaScript 中唯一值的集合。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。