Map.prototype.getOrInsertComputed()
Baseline
2026
Newly available
Since February 2026, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
getOrInsertComputed() は Map インスタンスのメソッドで、この対応表 (Map) 内で指定されたキーに対応する値を返します。キーが存在しない場合、指定されたコールバックから計算されたデフォルト値と共にキーを持つ新しい項目を挿入し、挿入された値を返します。
デフォルト値の計算コストが高い場合、実際に必要でない限り計算を避けることができるときは、Map.prototype.getOrInsert() の代わりにこのメソッドを使用してください。
試してみましょう
const map = new Map([["bar", "foo"]]);
const defaultCreator = (key) => `default for ${key}`;
console.log(map.getOrInsertComputed("bar", defaultCreator));
// 予想される結果: "foo"
console.log(map.getOrInsertComputed("baz", defaultCreator));
// 予想される結果: "default for baz"
構文
js
getOrInsertComputed(key, callback)
引数
返値
この Map オブジェクト内の指定されたキーに関連付けられた値です。キーが見つからなかった場合は、callback(key) の結果が追加され返されます。
例外
TypeError-
callbackが呼び出し可能でない場合に発生します。
例
>不要なデフォルトの計算を避ける
Map.prototype.getOrInsert() を使用した場合、必要でなくても毎回デフォルト値が計算されます。一方、getOrInsertComputed() を使用すると、デフォルト値は必要な場合にのみ計算されます。
js
const map = new Map([["bar", "foo"]]);
const defaultCreator = (key) => {
console.log(`${key} のデフォルト値を作成`);
return `default for ${key}`;
};
map.getOrInsert("bar", defaultCreator("bar")); // "bar のデフォルト値を作成" と出力
map.getOrInsertComputed("bar", defaultCreator); // 出力なし
仕様書
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-map.prototype.getorinsertcomputed> |