Set.prototype.isDisjointFrom()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Set 实例的 isDisjointFrom() 方法接受一个集合并返回一个布尔值,指示该集合是否没有与给定集合相同的元素。

¥The isDisjointFrom() method of Set instances takes a set and returns a boolean indicating if this set has no elements in common with the given set.

语法

¥Syntax

js
isDisjointFrom(other)

参数

¥Parameters

other

Set 对象或 set-like 对象。

返回值

¥Return value

如果该集合与 other 集合没有共同元素,则为 true,否则为 false

¥true if this set has no elements in common with the other set, and false otherwise.

描述

¥Description

如果两个集合没有共同元素,则它们是不相交的。用数学符号表示:

¥Two sets are disjoint if they have no elements in common. In mathematical notation:

A  is disjoint from  B A B = A\text{ is disjoint from }B \Leftrightarrow A\cap B = \empty

并使用维恩图:

¥And using Venn diagram:

A Venn diagram with two circles. A and B are disjoint because the circles have no region of overlap.

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

¥isDisjointFrom() 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,则它通过调用其 keys() 方法来迭代 other,如果 other 中的任何元素出现在 this 中,则返回 false(并通过调用其 return() 方法关闭 keys() 迭代器)。否则,返回 true
  • 否则,它会迭代 this 中的元素,如果 this 中的任何元素 e 导致 other.has(e) 返回 truthy 值,则返回 false。否则,返回 true

由于这种实现,isDisjointFrom() 的效率主要取决于 thisother 之间较小集合的大小(假设可以在亚线性时间内访问集合)。

¥Because of this implementation, the efficiency of isDisjointFrom() mostly depends on the size of the smaller set between this and other (assuming sets can be accessed in sublinear time).

示例

¥Examples

使用 isDisjointFrom()

¥Using isDisjointFrom()

完全平方集 (<20) 与素数集 (<20) 不相交,因为根据定义,完全平方可分解为两个整数的乘积,而 1 也不被视为素数:

¥The set of perfect squares (<20) is disjoint from the set of prime numbers (<20), because a perfect square is by definition decomposable into the product of two integers, while 1 is also not considered a prime number:

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 完全平方数都是合数:

¥The set of perfect squares (<20) is not disjoint from the set of composite numbers (<20), because all non-1 perfect squares are by definition composite numbers:

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
Set methods
# sec-set.prototype.isDisjointFrom

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看