Set.prototype.symmetricDifference()

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 实例的 symmetricDifference() 方法接受一个集合并返回一个新集合,其中包含位于该集合或给定集合中的元素,但不同时位于两者中。

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

语法

¥Syntax

js
symmetricDifference(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

一个新的 Set 对象,包含位于此集合或 other 集合中的元素,但不同时位于这两个集合中。

¥A new Set object containing elements which are in either this set or the other set, but not in both.

描述

¥Description

在数学符号中,对称差定义为:

¥In mathematical notation, symmetric difference is defined as:

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

并使用维恩图:

¥And using Venn diagram:

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

¥symmetricDifference() 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 that are not seen in other, and all elements in other that are not seen in this.

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

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

示例

¥Examples

使用 symmetryDifference()

¥Using symmetricDifference()

以下示例计算偶数集 (<10) 和完全平方集 (<10) 之间的对称差。结果是一组数字要么是偶数,要么是完全平方数,但不能两者兼而有之。

¥The following example computes the symmetric difference 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, but not both.

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 }

规范

Specification
Set methods
# sec-set.prototype.symmetricDifference

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看