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