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

浏览器兼容性

另见