Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. Set
  6. Set.prototype.union()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Set.prototype.union()

Baseline 2024
Newly available

Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Set 实例的union() 方法接受一个集合并返回包含当前集合与给定集合中存在的所有元素的新集合。

语法

js
union(other)

参数

other

一个Set类集合对象。

返回值

一个新的Set 对象,包含当前集合与other 中存在的所有元素。

描述

使用数学记号,并集的定义如下:

AB={xxA or xB}A\cup B = {x\midx\in A\text{ or }x\in B}

使用维恩图表示:

有部分重叠的两个圆的维恩图。A 和 B 的并集是被任意一个圆包含的区域。

union() 接受类集合对象作为other 参数。方法要求this 是一个Set 的实例,因为它不调用任何用户代码而直接获取this 中存储的数据。然后,它通过调用otherkeys() 方法迭代other,并构造一个新的集合。这个集合首先包含所有来自this 的元素,然后是所有在other 里但不在this 里的元素。

返回的集合里的元素的顺序首先是this 中的元素,其次是other 中的元素。

示例

使用 union()

下面的代码展示了如何得到小于 10 的偶数集和小于 10 的完全平方数集的并集。返回的并集其中的元素是偶数或者是完全平方数。

js
const evens = new Set([2, 4, 6, 8]);const squares = new Set([1, 4, 9]);console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 }

规范

Specification
ECMAScript® 2026 Language Specification
# sec-set.prototype.union

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp