语法
js
isSupersetOf(other)
参数
返回值
如果 other set 中的所有元素也都存在于此 set 中,则返回 true,否则返回 false。
描述
在数学表示法中,超集 定义为
使用维恩图表示:
注意: 超集 关系不等于真超集,这意味着如果 this 和 other 包含相同的元素,isSupersetOf() 也会返回 true。
isSupersetOf() 接受 类 Set 对象作为 other 参数。它要求 this 是一个实际的 Set 实例,因为它直接检索 this 中存储的底层数据,而无需调用任何用户代码。然后,其行为取决于 this 和 other 的大小。
- 如果
this中的元素数量少于other.size,则直接返回false。 - 否则,它会通过调用
other的keys()方法来迭代other,如果other中的任何元素不在this中,则返回false(并通过调用其return()方法关闭keys()迭代器)。否则,返回true。
示例
使用 isSupersetOf()
偶数集合(<20)是 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 是素数但不是奇数
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
相等的集合互为超集
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
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-set.prototype.issupersetof |
浏览器兼容性
加载中…