試一試
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 |
瀏覽器相容性
載入中…