Set.prototype.isDisjointFrom()
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 实例的 isDisjointFrom() 方法接受一个集合并返回一个布尔值来指示当前集合与给定集合是否不存在公共元素。
语法
js
isDisjointFrom(other)
参数
返回值
如果当前集合与 other 集合没有公共元素,则返回 true;否则返回 false。
描述
如果两个集合没有公共元素,那么它们是不相交的。使用数学记号:
使用维恩图表示:
isDisjointFrom() 接受类集合对象作为 other 参数。方法要求 this 是一个 Set 的实例,因为它不调用任何用户代码而直接获取 this 中存储的数据。然后,方法的行为取决于 this 和 other 的元素数量:
- 如果
this中的元素数量比other.size大,那么它将调用other的keys()方法遍历other。如果other中有任何元素出现在this中,方法返回false(并且通过调用keys()迭代器的return()方法关闭迭代器);否则,返回true。 - 否则,它将遍历
this。如果有任何元素e使得other.has(e)返回真值,方法返回false;否则,返回true。
由于这种实现,isDisjointFrom() 的效率主要取决于 this 和 other 中数量较少的集合(假定两个集合都能以次线性时间复杂度访问)。
示例
>使用 isDisjointFrom()
小于 20 的完全平方数集和小于 20 的质数集是不相交的,因为按定义完全平方数可分解为两个整数的乘积,而且 1 不是质数:
js
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const squares = new Set([1, 4, 9, 16]);
console.log(primes.isDisjointFrom(squares)); // true
而小于 20 的完全平方数集和小于 20 的合数集是相交的,因为按定义除 1 以外的完全平方数都是合数:
js
const composites = new Set([4, 6, 8, 9, 10, 12, 14, 15, 16, 18]);
const squares = new Set([1, 4, 9, 16]);
console.log(composites.isDisjointFrom(squares)); // false
规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-set.prototype.isdisjointfrom> |
浏览器兼容性
Loading…