在 JavaScript 中获取两个集合的并集
How to get the Union of Two Sets in JavaScript
要获得两个 Set 的并集,请使用扩展语法 (…) 将 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()
构造函数,所有重复项都将被忽略。
The
Set()
constructor takes an iterable object as a parameter, so an array is perfect.
Get a Union of Two Sets using for of loop #
To get a union of two Sets, pass the first Set
to the Set()
constructor to
create a third Set
. Then use the for...of
loop to iterate over the second
Set
and add each element to the newly created Set
. The new Set
will
contain a union of the other two Sets.
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'}
We created a reusable function that returns the union of two Sets.
The first step is to create a new Set
from the first Set
.
Then, we used the
for…of
loop to iterate over the second Set
and add its values to the new Set
.