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.

add() 會在一個 Set 物件的尾端加上一個指定 value 的新元素。

嘗試一下

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
mySet.add(value);

參數

value

要被加到 Set 物件中的值。

回傳值

Set 物件本身。

範例

使用 add 方法

js
var mySet = new Set();

mySet.add(1);
mySet.add(5).add("some text"); // chainable

console.log(mySet);
// Set [1, 5, "some text"]

規範

Specification
ECMAScript® 2025 Language Specification
# sec-set.prototype.add

瀏覽器相容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
add

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

參見