Set() 构造函数
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Set() 构造函数创建 Set 对象。
尝试一下
const set1 = new Set([1, 2, 3, 4, 5]);
console.log(set1.has(1));
// Expected output: true
console.log(set1.has(5));
// Expected output: true
console.log(set1.has(6));
// Expected output: false
语法
js
new Set()
new Set(iterable)
参数
iterable可选-
如果传入一个可迭代对象,它的所有元素将不重复地被添加到新的
Set中。如果不指定此参数或其值为null,则新的Set为空。
返回值
一个新的 Set 对象。
示例
>使用 Set 对象
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® 2026 Language Specification> # sec-set-constructor> |
浏览器兼容性
Loading…