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.
语法
参数
返回值
描述
¥Description
在数学符号中,对称差定义为:
¥In mathematical notation, symmetric difference is defined as:
并使用维恩图:
¥And using Venn diagram:
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
.
示例
使用 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.
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 |
浏览器兼容性
BCD tables only load in the browser