Set.prototype.add()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Set
实例的 add()
方法会在该集合中插入一个具有指定值的新元素,如果该 Set
对象中没有具有相同值的元素。
尝试一下
const set1 = new Set();
set1.add(42);
set1.add(42);
set1.add(13);
for (const item of set1) {
console.log(item);
// Expected output: 42
// Expected output: 13
}
语法
js
add(value)
参数
value
-
要添加到
Set
对象的元素的值。
返回值
添加了值的 Set
对象。
示例
使用 add() 方法
js
const mySet = new Set();
mySet.add(1);
mySet.add(5).add("some text"); // 可以链式调用
console.log(mySet);
// Set [1, 5, "some text"]
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-set.prototype.add |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
add |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.