Set.prototype.intersection()

Baseline 2024
新推出

自 2024 年 6 月起,此功能已在最新的设备和浏览器版本中可用。此功能可能不适用于较旧的设备或浏览器。

intersection() 方法是 Set 实例的一个方法,它接受一个集合作为参数,并返回一个新的集合,该集合包含此集合和给定集合中的所有元素。

语法

js
intersection(other)

参数

其他

一个 Set 对象,或 类 Set 对象

返回值

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

描述

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

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

使用维恩图表示:

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

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

  • 如果 this 中的元素比 other.size 多,则它会通过调用 otherkeys() 方法来迭代 other,并使用所有也存在于 this 中的元素构建一个新集合。
  • 否则,它会迭代 this 中的元素,并使用 this 中的所有元素 e 构建一个新集合,这些元素会使 other.has(e) 返回一个 真值

由于这种实现方式,intersection() 的效率很大程度上取决于 thisother 中较小集合的大小(假设集合可以以亚线性时间访问)。返回集合中元素的顺序与 thisother 中较小集合的顺序相同。

示例

使用 intersection()

下面的示例计算了奇数集(小于 10)和完全平方数集(小于 10)之间的交集。结果是既是奇数又是完全平方数的集合。

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 }

规范

规范
ECMAScript® 2026 语言规范
# sec-set.prototype.intersection

浏览器兼容性

另见