WeakMap.prototype.getOrInsert()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

WeakMap 例項的 getOrInsert() 方法會返回此 WeakMap 中與指定鍵對應的。如果鍵不存在,它會使用給定的預設值插入一個新條目,並返回插入的值。

如果預設值的計算成本很高,請考慮改用 WeakMap.prototype.getOrInsertComputed(),它接受一個回撥函式,僅在實際需要時計算預設值。

試一試

const map = new WeakMap([[window, "foo"]]);
console.log(map.getOrInsert(window, "default"));
// Expected output: "foo"

console.log(map.getOrInsert({}, "default"));
// Expected output: "default"

語法

js
getOrInsert(key, defaultValue)

引數

key

要從 WeakMap 物件返回的值的鍵。必須是物件或 未註冊的 Symbol。物件鍵透過 引用 進行比較,而不是透過值。

defaultValue

如果鍵尚不存在於 WeakMap 物件中,則要插入並返回的值。

返回值

WeakMap 物件中與指定鍵關聯的值。如果找不到鍵,則返回 undefined

異常

TypeError

如果 key 不是物件或 未註冊的 Symbol,則會丟擲錯誤。

示例

使用 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"

規範

規範
Upsert (更新或插入)
# sec-weakmap.prototype.getOrInsert

瀏覽器相容性

另見