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() 方法接受一个集合并返回一个新集合,其中包含该集合和给定集合中的一个或两个中的元素。

¥The union() method of Set instances takes a set and returns a new set containing elements which are in either or both of this set and the given set.

语法

¥Syntax

js
union(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

一个新的 Set 对象,包含此集合和 other 集合中的一个或两个中的元素。

¥A new Set object containing elements which are in either or both of this set and the other set.

描述

¥Description

在数学符号中,并集定义为:

¥In mathematical notation, union is defined as:

A B = { x x A  or  x B } A\cup B = {x\midx\in A\text{ or }x\in B}

并使用维恩图:

¥And using Venn diagram:

A Venn diagram where two circles overlap. The symmetric difference of A and B is the region contained by either or both circles.

union() 接受 set-like 对象作为 other 参数。它要求 this 是一个实际的 Set 实例,因为它直接检索存储在 this 中的底层数据,而不调用任何用户代码。然后,它通过调用 keys() 方法来迭代 other,并构造一个新集合,其中包含 this 中的所有元素,后跟 other 中不存在于 this 中的所有元素。

¥union() accepts set-like objects as the other parameter. It requires this to be an actual Set instance, because it directly retrieves the underlying data stored in this without invoking any user code. Then, it iterates over other by calling its keys() method, and constructs a new set with all elements in this, followed by all elements in other that are not present in this.

返回集合中元素的顺序是首先是 this 中的元素,然后是 other 中的元素。

¥The order of elements in the returned set is first those in this followed by those in other.

示例

¥Examples

使用 union()

¥Using union()

以下示例计算偶数集 (<10) 和完全平方集 (<10) 之间的并集。结果是一组数字,或者是偶数,或者是完全平方数,或者两者兼而有之。

¥The following example computes the union between the set of even numbers (<10) and the set of perfect squares (<10). The result is the set of numbers that are either even or a perfect square, or both.

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
Set methods
# sec-set.prototype.union

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看