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.
语法
参数
返回值
描述
¥Description
在数学符号中,差异定义为:
¥In mathematical notation, difference is defined as:
并使用维恩图:
¥And using Venn diagram:
difference()
接受 set-like 对象作为 other
参数。它要求 this
是一个实际的 Set
实例,因为它直接检索存储在 this
中的底层数据,而不调用任何用户代码。然后,它的行为取决于 this
和 other
的大小:
¥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
.
示例
使用差异()
¥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.
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 |
浏览器兼容性
BCD tables only load in the browser