Set.prototype.union()
Baseline
2024
Newly 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()
方法接受一个集合并返回包含当前集合与给定集合中存在的所有元素的新集合。
语法
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> |
浏览器兼容性
Loading…