Set.prototype.isSubsetOf()

Baseline 2024
新推出

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

isSubsetOf() 方法是 Set 例項的一個方法,它接受一個集合作為引數,並返回一個布林值,指示該集合的所有元素是否都包含在給定的集合中。

語法

js
isSubsetOf(other)

引數

其他

一個 Set 物件,或 類 Set 物件

返回值

如果該集合中的所有元素也存在於 other 集合中,則返回 true,否則返回 false

描述

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

ABxA,xBA\subseteq B \Leftrightarrow \forall x\in A,\,x\in B

使用維恩圖表示:

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

注意: 子集 關係不是 *真子集* 關係,這意味著如果 thisother 包含相同的元素,isSubsetOf() 也會返回 true

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

  • 如果 this 中的元素比 other.size 多,則直接返回 false
  • 否則,它會遍歷 this 中的元素,如果 this 中的任何元素 e 導致 other.has(e) 返回 假值,則返回 false。否則,返回 true

示例

使用 isSubsetOf()

4 的倍數集合 (<20) 是偶數集合 (<20) 的子集

js
const fours = new Set([4, 8, 12, 16]);
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(fours.isSubsetOf(evens)); // 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(primes.isSubsetOf(odds)); // false

相等的集合是彼此的子集

js
const set1 = new Set([1, 2, 3]);
const set2 = new Set([1, 2, 3]);
console.log(set1.isSubsetOf(set2)); // true
console.log(set2.isSubsetOf(set1)); // true

規範

規範
ECMAScript® 2026 語言規範
# sec-set.prototype.issubsetof

瀏覽器相容性

另見