Set.prototype.intersection()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used 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.

语法

¥Syntax

js
intersection(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

一个新的 Set 对象,包含该集合和 other 集合中的元素。

¥A new Set object containing elements in both this set and the other set.

描述

¥Description

在数学符号中,交集定义为:

¥In mathematical notation, intersection is defined as:

A B = { x A x B } A\cap B = {x\in A\mid x\in B}

并使用维恩图:

¥And using Venn diagram:

A Venn diagram where two circles overlap. The intersection of A and B is the part where they overlap.

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

¥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() 的效率主要取决于 thisother 之间较小集合的大小(假设可以在亚线性时间内访问集合)。返回集合中元素的顺序与 thisother 中较小者的顺序相同。

¥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.

示例

¥Examples

使用交集()

¥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.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看