此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Set.prototype.union()
Baseline 2024Newly available
Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Set 实例的union() 方法接受一个集合并返回包含当前集合与给定集合中存在的所有元素的新集合。
In this article
语法
js
union(other)参数
返回值
一个新的Set 对象,包含当前集合与other 中存在的所有元素。
描述
使用数学记号,并集的定义如下:
使用维恩图表示:
union() 接受类集合对象作为other 参数。方法要求this 是一个Set 的实例,因为它不调用任何用户代码而直接获取this 中存储的数据。然后,它通过调用other 的keys() 方法迭代other,并构造一个新的集合。这个集合首先包含所有来自this 的元素,然后是所有在other 里但不在this 里的元素。
返回的集合里的元素的顺序首先是this 中的元素,其次是other 中的元素。
示例
>使用 union()
下面的代码展示了如何得到小于 10 的偶数集和小于 10 的完全平方数集的并集。返回的并集其中的元素是偶数或者是完全平方数。
js
const evens = new Set([2, 4, 6, 8]);const squares = new Set([1, 4, 9]);console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 }规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-set.prototype.union> |