Set.prototype.intersection()

Baseline 2024
新推出

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

intersection() 方法是 Set 例項的一個方法,它接受一個集合作為引數,並返回一個新的集合,該集合包含此集合和給定集合中的所有元素。

語法

js
intersection(other)

引數

其他

一個 Set 物件,或 類 Set 物件

返回值

一個新的 Set 物件,包含此集合和 other 集合中的所有元素。

描述

在數學符號中,交集 定義為

AB={xAxB}A\cap B = \{x\in A\mid x\in B\}

使用維恩圖表示:

A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap.

intersection() 方法接受 類集合 物件作為 other 引數。它要求 this 是一個實際的 Set 例項,因為它直接檢索儲存在 this 中的底層資料,而不呼叫任何使用者程式碼。然後,其行為取決於 thisother 的大小。

  • 如果 this 中的元素比 other.size 多,則它會透過呼叫 otherkeys() 方法來迭代 other,並使用所有也存在於 this 中的元素構建一個新集合。
  • 否則,它會迭代 this 中的元素,並使用 this 中的所有元素 e 構建一個新集合,這些元素會使 other.has(e) 返回一個 真值

由於這種實現方式,intersection() 的效率很大程度上取決於 thisother 中較小集合的大小(假設集合可以以亞線性時間訪問)。返回集合中元素的順序與 thisother 中較小集合的順序相同。

示例

使用 intersection()

下面的示例計算了奇數集(小於 10)和完全平方數集(小於 10)之間的交集。結果是既是奇數又是完全平方數的集合。

js
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.intersection(squares)); // Set(2) { 1, 9 }

規範

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

瀏覽器相容性

另見