Set.prototype.union()

Baseline 2024
新推出

自 2024 年 6 月起,此功能已在最新的裝置和瀏覽器版本中可用。此功能可能不適用於較舊的裝置或瀏覽器。

union() 方法是 Set 例項的一個方法,它接收一個 Set,並返回一個新的 Set,其中包含此 Set 和給定 Set 中任一或兩者都存在的元素。

語法

js
union(other)

引數

其他

一個 Set 物件,或 類 Set 物件

返回值

一個新的 Set 物件,其中包含此 Set 和 other Set 中任一或兩者都存在的元素。

描述

在數學表示法中,並集 定義為

AB={xxA 或 xB}A\cup B = \{x\mid x\in A\text{ 或 }x\in B\}

使用維恩圖表示:

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 物件作為 other 引數。它要求 this 是一個實際的 Set 例項,因為它直接檢索儲存在 this 中的底層資料,而無需呼叫任何使用者程式碼。然後,它透過呼叫 otherkeys() 方法來迭代 other,並構造一個包含 this 中所有元素的新 Set,然後新增 other 中不存在於 this 中的所有元素。

返回的 Set 中元素的順序是:首先是 this 中的元素,然後是 other 中的元素。

示例

使用 union()

下面的示例計算小於 10 的偶數 Set 與小於 10 的完全平方數 Set 的並集。結果是那些是偶數或完全平方數(或兩者都是)的數字的 Set。

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 }

規範

規範
ECMAScript® 2026 語言規範
# sec-set.prototype.union

瀏覽器相容性

另見