迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中获得两个集合的并集

作者:迹忆客 最近更新:2022/11/18 浏览次数:

要获得两个集合的并集,请使用扩展语法 ... 将 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'}

javascript 求两个集合的并集

我们使用扩展语法 ... 将两个 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() 构造函数,所有重复项都将被忽略。

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 循环获取两个集合的并集

我们创建了一个可重用的函数,它返回两个集合的并集。

第一步是从第一个集合创建一个新集合。

然后,我们使用 for...of 循环迭代第二个 Set 并将其值添加到新 Set 中。

集合不存储重复值,所以我们不必担心处理它。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便