Set.prototype.difference()

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

¥The difference() method of Set instances takes a set and returns a new set containing elements in this set but not in the given set.

语法

¥Syntax

js
difference(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

一个新的 Set 对象,包含此集合中但不包含 other 集合中的元素。

¥A new Set object containing elements in this set but not in the other set.

描述

¥Description

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

¥In mathematical notation, difference is defined as:

A B = { x A x B } A\setminus B = {x\in A\mid x\notin B}

并使用维恩图:

¥And using Venn diagram:

A Venn diagram where two circles overlap. The difference of A and B is the part of A that is not overlapping B.

difference() 接受 set-like 对象作为 other 参数。它要求 this 是一个实际的 Set 实例,因为它直接检索存储在 this 中的底层数据,而不调用任何用户代码。然后,它的行为取决于 thisother 的大小:

¥difference() 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, its behavior depends on the sizes of this and other:

  • 如果 this 中的元素多于 other.size,则它通过调用其 keys() 方法来迭代 other,并使用 this 中所有在 other 中看不到的元素构造一个新集合。
  • 否则,它会迭代 this 中的元素,并使用 this 中的所有元素 e 构造一个新集合,导致 other.has(e) 返回 falsy 值。

返回集合中元素的顺序与 this 中的相同。

¥The order of elements in the returned set is the same as in this.

示例

¥Examples

使用差异()

¥Using difference()

以下示例计算奇数集 (<10) 与完全平方集 (<10) 之间的差。结果是一组不是完美平方的奇数。

¥The following example computes the difference between the set of odd numbers (<10) and the set of perfect squares (<10). The result is the set of odd numbers that are not perfect squares.

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

规范

Specification
Set methods
# sec-set.prototype.difference

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看