Set.prototype.symmetricDifference()

Baseline 2024
新推出

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

symmetricDifference() 方法是 Set 例項的一個方法,它接收一個集合作為引數,並返回一個新的集合,其中包含只存在於其中一個集合(即當前集合或給定的集合)中,而不在兩個集合中都存在的元素。

語法

js
symmetricDifference(other)

引數

其他

一個 Set 物件,或 類 Set 物件

返回值

一個包含只存在於當前集合或 other 集合中,而不在兩個集合中都存在的元素的新的 Set 物件。

描述

在數學表示法中,對稱差 定義為

AB=(AB)(BA)A\ominus B = (A\setminus B)\cup(B\setminus A)

使用維恩圖表示:

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

symmetricDifference()類 Set 物件 作為 other 引數。它要求 this 是一個實際的 Set 例項,因為它會直接檢索 this 中儲存的底層資料,而不會呼叫任何使用者程式碼。然後,它透過呼叫 otherkeys() 方法來迭代 other,並構建一個新集合,其中包含 this 中所有未在 other 中出現過的元素,以及 other 中所有未在 this 中出現過的元素。

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

示例

使用 symmetricDifference()

以下示例計算小於 10 的偶數集合與小於 10 的完全平方數集合的對稱差。結果是那些是偶數或完全平方數,但不是兩者兼有的數字的集合。

js
const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.symmetricDifference(squares)); // Set(5) { 2, 6, 8, 1, 9 }

規範

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

瀏覽器相容性

另見