如何在 JavaScript 中获得两个集合的并集
要获得两个集合的并集,请使用扩展语法 ...
将 Set 的值解包到一个数组中,并将结果传递给 Set()
构造函数,例如 new Set([...set1, ...set2])
。 新 Set 将包含其他两个的并集。
const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['a', 'b', 'd']);
const union = new Set([...set1, ...set2]);
console.log(union); // 👉️ {'a', 'b', 'c', 'd'}
我们使用扩展语法 ...
将两个 Set 对象的值解包到一个数组中。
const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['a', 'b', 'd']);
const arr = [...set1, ...set2];
console.log(arr); // 👉️ ['a', 'b', 'c' ,'a', 'b', 'd']
数组存储重复值而不是 Set。 一旦将数组传递给 Set()
构造函数,所有重复项都将被忽略。
Set()
构造函数将一个可迭代对象作为参数,因此数组是完美的。
使用 for of 循环获取两个集合的并集
要获得两个 Set 的并集,请将第一个 Set 传递给 Set()
构造函数以创建第三个 Set。 然后使用 for...of
循环遍历第二个 Set 并将每个元素添加到新创建的 Set 中。 新 Set 将包含其他两个 Set 的并集。
function getUnion(setA, setB) {
const union = new Set(setA);
for (const element of setB) {
union.add(element);
}
return union;
}
const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['a', 'b', 'd']);
console.log(getUnion(set1, set2)); // 👉️ {'a', 'b', 'c', 'd'}
我们创建了一个可重用的函数,它返回两个集合的并集。
第一步是从第一个集合创建一个新集合。
然后,我们使用 for...of
循环迭代第二个 Set 并将其值添加到新 Set 中。
集合不存储重复值,所以我们不必担心处理它。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。