WeakSet.prototype.add()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

add() 方法(WeakSet 例項的)會將指定值新增到此集合中,如果該值尚不存在。

試一試

const weakset = new WeakSet();
const object = {};

weakset.add(object);
console.log(weakset.has(object));
// Expected output: true

try {
  weakset.add(1);
} catch (error) {
  console.log(error);
  // Expected output (Chrome): TypeError: Invalid value used in weak set
  // Expected output (Firefox): TypeError: WeakSet value must be an object, got 1
  // Expected output (Safari): TypeError: Attempted to add a non-object key to a WeakSet
}

語法

js
add(value)

引數

value

要新增到 WeakSet 物件的值。必須是物件或未註冊的 Symbol。物件是按引用比較,而不是按值比較。

返回值

WeakSet 物件。

異常

TypeError

如果 value 不是物件或未註冊的 Symbol,則會丟擲此錯誤。

示例

使用 add()

js
const ws = new WeakSet();

ws.add(window); // add the window object to the WeakSet

ws.has(window); // true

// WeakSet only takes objects as arguments
ws.add(1);
// results in "TypeError: Invalid value used in weak set" in Chrome
// and "TypeError: 1 is not a non-null object" in Firefox

規範

規範
ECMAScript® 2026 語言規範
# sec-weakset.prototype.add

瀏覽器相容性

另見