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.
语法
参数
返回值
描述
¥Description
在数学符号中,子集定义为:
¥In mathematical notation, subset is defined as:
并使用维恩图:
¥And using Venn diagram:
注意:子集关系不是真子集,这意味着如果
this
和other
包含相同元素,则isSubsetOf()
返回true
。¥Note: The subset relationship is not proper subset, which means
isSubsetOf()
returnstrue
ifthis
andother
contain the same elements.
isSubsetOf()
接受 set-like 对象作为 other
参数。它要求 this
是一个实际的 Set
实例,因为它直接检索存储在 this
中的底层数据,而不调用任何用户代码。然后,它的行为取决于 this
和 other
的大小:
¥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
。
示例
使用 isSubsetOf()
¥Using isSubsetOf()
4 的倍数集 (<20) 是偶数 (<20) 的子集:
¥The set of multiples of 4 (<20) is a subset of even numbers (<20):
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:
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:
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 |
浏览器兼容性
BCD tables only load in the browser