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

浏览器兼容性

另见