WeakSet.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 September 2015.
add()
メソッドは、新しい要素を WeakSet
オブジェクトの最後に追加します。
試してみましょう
const weakset1 = new WeakSet();
const object1 = {};
weakset1.add(object1);
console.log(weakset1.has(object1));
// Expected output: true
try {
weakset1.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
}
構文
ws.add(value);
引数
value
-
必須。
WeakSet
コレクションに追加する要素の値です。
返値
WeakSet
オブジェクトです。
例
add() の使用
js
var ws = new WeakSet();
ws.add(window); //window オブジェクトを WeakSet へ追加
ws.has(window); // true
// WeakSet は引数としてオブジェクトのみを取ります。
ws.add(1);
// 結果は "TypeError: Invalid value used in weak set" (Chrome)
// "TypeError: 1 is not a non-null object" (Firefox)
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-weakset.prototype.add |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
add |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.