Set.prototype.intersection()
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
实例的 intersection()
方法接受一个集合并返回一个新集合,其中包含该集合和给定集合中的元素。
¥The intersection()
method of Set
instances takes a set and returns a new set containing elements in both this set and the given set.
语法
参数
返回值
描述
¥Description
在数学符号中,交集定义为:
¥In mathematical notation, intersection is defined as:
并使用维恩图:
¥And using Venn diagram:
intersection()
接受 set-like 对象作为 other
参数。它要求 this
是一个实际的 Set
实例,因为它直接检索存储在 this
中的底层数据,而不调用任何用户代码。然后,它的行为取决于 this
和 other
的大小:
¥intersection()
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
中也存在的所有生成元素构造一个新集合。 - 否则,它会迭代
this
中的元素,并使用this
中的所有元素e
构造一个新集合,导致other.has(e)
返回 truthy 值。
由于这种实现,intersection()
的效率主要取决于 this
和 other
之间较小集合的大小(假设可以在亚线性时间内访问集合)。返回集合中元素的顺序与 this
和 other
中较小者的顺序相同。
¥Because of this implementation, the efficiency of intersection()
mostly depends on the size of the smaller set between this
and other
(assuming sets can be accessed in sublinear time). The order of elements in the returned set is the same as that of the smaller of this
and other
.
示例
使用交集()
¥Using intersection()
以下示例计算奇数集 (<10) 与完全平方集 (<10) 之间的交集。结果是一组完全平方的奇数。
¥The following example computes the intersection between the set of odd numbers (<10) and the set of perfect squares (<10). The result is the set of odd numbers that are perfect squares.
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.intersection(squares)); // Set(2) { 1, 9 }
规范
Specification |
---|
Set methods # sec-set.prototype.intersection |
浏览器兼容性
BCD tables only load in the browser