Set() 构造函数

Set() 构造函数创建 Set 对象。

¥The Set() constructor creates Set objects.

Try it

语法

¥Syntax

js
new Set()
new Set(iterable)

注意:Set() 只能与 new 一起构建。尝试在没有 new 的情况下调用它会抛出 TypeError

¥Note: Set() can only be constructed with new. Attempting to call it without new throws a TypeError.

参数

¥Parameters

iterable Optional

如果一个 可迭代对象 被传递,它的所有元素将被添加到新的 Set 中。

如果不指定该参数,或者其值为 null,则新的 Set 为空。

返回值

¥Return value

一个新的 Set 对象。

¥A new Set object.

示例

¥Examples

使用 Set 对象

¥Using the Set object

js
const mySet = new Set();

mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add("some text"); // Set [ 1, 5, 'some text' ]
const o = { a: 1, b: 2 };
mySet.add(o);

规范

Specification
ECMAScript Language Specification
# sec-set-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看