A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set/union below:

Set.prototype.union() - JavaScript | MDN

Set.prototype.union()

Baseline 2024

Newly available

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

语法 参数
other

一个 Set 或类集合对象。

返回值

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

描述

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

A ∪ B = { x ∣ x ∊ A  or  x ∊ B } A\cup B = {x\midx\in A\text{ or }x\in B}

使用维恩图表示:

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

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

示例 使用 union()

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

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 }
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4