大网数据广告活动
Web 标准与前端开发

Set.prototype.isSubsetOf()

· 52CE 我爱测

The **`isSubsetOf()`** method of Set instances takes a set and returns a boolean indicating if all elements of this set are in the given set.

The isSubsetOf() method of Set instances takes a set and returns a boolean indicating if all elements of this set are in the given set.

Syntax

isSubsetOf(other)

Parameters

  • other

Return value

true if all elements in this set are also in the other set, and false otherwise.

Description

In mathematical notation, subset is defined as:

<math display="block"> <semantics><mrow><mi>A</mi><mo>⊆</mo><mi>B</mi><mo stretchy="false">⇔</mo><mo>∀</mo><mi>x</mi><mo>∊</mo><mi>A</mi><mo>,</mo><mspace width="0.16666666666666666em"></mspace><mi>x</mi><mo>∊</mo><mi>B</mi></mrow><annotation encoding="TeX">A\subseteq B \Leftrightarrow \forall x\in A,,x\in B</annotation></semantics> </math>

And using Venn diagram:

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

[!NOTE] The subset relationship is not proper subset, which means isSubsetOf() returns true if this and other contain the same elements.

isSubsetOf() 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:

  • If there are more elements in this than other.size, then it directly returns false.
  • Otherwise, it iterates over the elements in this, and returns false if any element e in this causes other.has(e) to return a falsy value. Otherwise, it returns true.

Examples

Using isSubsetOf()

The set of multiples of 4 (<20) is a subset of even numbers (<20):

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

The set of prime numbers (<20) is not a subset of all odd numbers (<20), because 2 is prime but not odd:

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

Equivalent sets are subsets of each other:

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

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。