Set.prototype.isSupersetOf()

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

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

语法

¥Syntax

js
isSupersetOf(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

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

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

描述

¥Description

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

¥In mathematical notation, superset is defined as:

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

并使用维恩图:

¥And using Venn diagram:

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

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

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

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

¥isSupersetOf() 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
  • 否则,它通过调用其 keys() 方法来迭代 other,并且如果 other 中的任何元素在 this 中不存在,则返回 false(并通过调用其 return() 方法关闭 keys() 迭代器)。否则,返回 true

示例

¥Examples

使用 isSupersetOf()

¥Using isSupersetOf()

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

¥The set of even numbers (<20) is a superset of multiples of 4 (<20):

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

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

¥The set of all odd numbers (<20) is not a superset of prime 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(odds.isSupersetOf(primes)); // false

等价集是彼此的超集:

¥Equivalent sets are supersets of each other:

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

规范

Specification
Set methods
# sec-set.prototype.isSupersetOf

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看