Set.prototype.isSubsetOf()

Baseline 2024
新推出

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

isSubsetOf() 方法是 Set 实例的一个方法,它接受一个集合作为参数,并返回一个布尔值,指示该集合的所有元素是否都包含在给定的集合中。

语法

js
isSubsetOf(other)

参数

其他

一个 Set 对象,或 类 Set 对象

返回值

如果该集合中的所有元素也存在于 other 集合中,则返回 true,否则返回 false

描述

在数学表示法中,子集 定义为

ABxA,xBA\subseteq B \Leftrightarrow \forall x\in A,\,x\in B

使用维恩图表示:

A Venn diagram with two circles. A is a subset of B because A is completely contained in B.

注意: 子集 关系不是 *真子集* 关系,这意味着如果 thisother 包含相同的元素,isSubsetOf() 也会返回 true

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

  • 如果 this 中的元素比 other.size 多,则直接返回 false
  • 否则,它会遍历 this 中的元素,如果 this 中的任何元素 e 导致 other.has(e) 返回 假值,则返回 false。否则,返回 true

示例

使用 isSubsetOf()

4 的倍数集合 (<20) 是偶数集合 (<20) 的子集

js
const fours = new Set([4, 8, 12, 16]);
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(fours.isSubsetOf(evens)); // true

素数集合 (<20) 不是所有奇数集合 (<20) 的子集,因为 2 是素数但不是奇数

js
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const odds = new Set([3, 5, 7, 9, 11, 13, 15, 17, 19]);
console.log(primes.isSubsetOf(odds)); // false

相等的集合是彼此的子集

js
const set1 = new Set([1, 2, 3]);
const set2 = new Set([1, 2, 3]);
console.log(set1.isSubsetOf(set2)); // true
console.log(set2.isSubsetOf(set1)); // true

规范

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

浏览器兼容性

另见