Set.prototype.isSupersetOf()

Baseline 2024
新推出

自 2024 年 6 月起,此功能已在最新的裝置和瀏覽器版本中可用。此功能可能不適用於較舊的裝置或瀏覽器。

isSupersetOf() 方法用於判斷一個 Set 例項是否包含另一個 set 中的所有元素,並返回一個布林值。

語法

js
isSupersetOf(other)

引數

其他

一個 Set 物件,或 類 Set 物件

返回值

如果 other set 中的所有元素也都存在於此 set 中,則返回 true,否則返回 false

描述

在數學表示法中,超集 定義為

ABxB,xAA\supseteq B \Leftrightarrow \forall x\in B,\,x\in A

使用維恩圖表示:

A Venn diagram with two circles. A is a superset of B because B is completely contained in A.

注意: 超集 關係不等於真超集,這意味著如果 thisother 包含相同的元素,isSupersetOf() 也會返回 true

isSupersetOf() 接受 類 Set 物件作為 other 引數。它要求 this 是一個實際的 Set 例項,因為它直接檢索 this 中儲存的底層資料,而無需呼叫任何使用者程式碼。然後,其行為取決於 thisother 的大小。

  • 如果 this 中的元素數量少於 other.size,則直接返回 false
  • 否則,它會透過呼叫 otherkeys() 方法來迭代 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

瀏覽器相容性

另見