试一试
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 |
浏览器兼容性
加载中…