Map.prototype.getOrInsert()
Map 例項的 getOrInsert() 方法返回此 Map 中與指定鍵對應的. 如果鍵不存在,它將使用給定的預設值插入一個新條目,並返回插入的值。
如果預設值的計算成本很高,請考慮使用 Map.prototype.getOrInsertComputed(),它接受一個回撥函式,僅在實際需要時才計算預設值。
試一試
const map = new Map([["bar", "foo"]]);
console.log(map.getOrInsert("bar", "default"));
// Expected output: "foo"
console.log(map.getOrInsert("baz", "default"));
// Expected output: "default"
語法
js
getOrInsert(key, defaultValue)
引數
key-
要從
Map物件返回的值的鍵。物件鍵透過引用進行比較,而不是按值進行比較。 defaultValue-
如果鍵尚不存在於
Map物件中,則插入並返回的值。
返回值
與 Map 物件中指定鍵關聯的值。如果找不到鍵,將插入並返回 defaultValue。
描述
getOrInsert() 方法等同於以下程式碼
js
if (map.has(key)) {
return map.get(key);
}
map.set(key, defaultValue);
return defaultValue;
它也類似於以下模式(如果 null 或 undefined 是對映中的有效值,則此模式的可靠性稍差)
js
map.set(key, map.get(key) ?? defaultValue);
示例
應用預設值
您可以使用 getOrInsert() 來確保鍵存在於對映中,即使您當前不需要它的值。這通常是為了規範化使用者輸入。
假設您有一個使用者偏好設定的對映,並且您希望確保某個偏好設定始終設定為預設值,如果使用者未指定它
js
const options = readConfig();
options.getOrInsert("theme", "light");
options.getOrInsert("fontSize", 14);
// Later in your code, you can safely assume these options exist
document.body.dataset.theme = options.get("theme");
規範
| 規範 |
|---|
| Upsert (更新或插入) # sec-map.prototype.getOrInsert |
瀏覽器相容性
載入中…