Set.prototype.isSubsetOf()

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 实例的 isSubsetOf() 方法接受一个集合并返回一个布尔值,指示该集合的所有元素是否都在给定集合中。

¥The isSubsetOf() method of Set instances takes a set and returns a boolean indicating if all elements of this set are in the given set.

语法

¥Syntax

js
isSubsetOf(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

如果该集合中的所有元素也在 other 集合中,则为 true,否则为 false

¥true if all elements in this set are also in the other set, and false otherwise.

描述

¥Description

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

¥In mathematical notation, subset is defined as:

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

并使用维恩图:

¥And using Venn diagram:

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

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

¥Note: The subset relationship is not proper subset, which means isSubsetOf() returns true if this and other contain the same elements.

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

¥isSubsetOf() 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,则直接返回 false
  • 否则,它会迭代 this 中的元素,如果 this 中的任何元素 e 导致 other.has(e) 返回 falsy 值,则返回 false。否则,返回 true

示例

¥Examples

使用 isSubsetOf()

¥Using isSubsetOf()

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

¥The set of multiples of 4 (<20) is a subset of even numbers (<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 是素数但不是奇数:

¥The set of prime numbers (<20) is not a subset of all odd numbers (<20), because 2 is prime but not odd:

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

等价集是彼此的子集:

¥Equivalent sets are subsets of each other:

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

规范

Specification
Set methods
# sec-set.prototype.isSubsetOf

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看