WeakMap.prototype.getOrInsert()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
getOrInsert() は WeakMap インスタンスのメソッドで、この WeakMap 内で指定されたキーに対応する値を返します。キーが存在しない場合、指定されたデフォルト値を持つ新しい項目を挿入し、挿入された値を返します。
デフォルト値の計算にコストがかかる場合は、代わりに WeakMap.prototype.getOrInsertComputed() を使用することを検討してください。これはコールバックを受け取り、実際に必要になった場合にのみデフォルト値を計算します。
試してみましょう
const map = new WeakMap([[window, "foo"]]);
console.log(map.getOrInsert(window, "default"));
// 予想される結果: "foo"
console.log(map.getOrInsert({}, "default"));
// 予想される結果: "default"
構文
js
getOrInsert(key, defaultValue)
引数
key-
WeakMapオブジェクトから値を取得する項目のキー。オブジェクトまたは非登録シンボルのどちらかでなければなりません。オブジェクトのキーは値ではなく参照として比較されます。 defaultValue-
キーが
WeakMapオブジェクト内に存在しなかった場合に、挿入して返す値です。
返値
この WeakMap オブジェクト内の指定されたキーに関連付けられた値です。キーが見つからなかった場合は、undefined が返されます。
例外
例
>getOrInsert() の使用
js
const wm = new WeakMap();
const obj = {};
console.log(wm.get(obj)); // undefined
console.log(wm.getOrInsert(obj, "default")); // "default"
console.log(wm.get(obj)); // "default"
console.log(wm.getOrInsert(obj, "another default")); // "default"
仕様書
| Specification |
|---|
| Upsert> # sec-weakmap.prototype.getOrInsert> |