Set 实例的 isDisjointFrom() 方法接受一个集合并返回一个布尔值来指示当前集合与给定集合是否不存在公共元素。
语法
isDisjointFrom(other)
参数
other- : 一个 Set 或类集合对象。
返回值
如果当前集合与 other 集合没有公共元素,则返回 true;否则返回 false。
描述
如果两个集合没有公共元素,那么它们是不相交的。使用数学记号:
<math display="block"><semantics><mrow><mi>A</mi><mtext> 与 </mtext><mi>B</mi><mtext> 不相交 </mtext><mo stretchy="false">⇔</mo><mi>A</mi><mo>∩</mo><mi>B</mi><mo>=</mo><mi>∅</mi></mrow><annotation encoding="TeX">A\text{ 与 }B \text{ 不相交 } \Leftrightarrow A\cap B = \empty</annotation></semantics></math>
使用维恩图表示:
有两个圆的维恩图。因为 A 和 B 没有重叠的部分,所以它们是不相交的。
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 不是质数:
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 以外的完全平方数都是合数:
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
规范
浏览器兼容性
参见
core-js中Set.prototype.isDisjointFrom的 polyfill- Set.prototype.difference()
- Set.prototype.intersection()
- Set.prototype.isSubsetOf()
- Set.prototype.isSupersetOf()
- Set.prototype.symmetricDifference()
- Set.prototype.union()
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
