Map.prototype.getOrInsertComputed()

可用性有限

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

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

getOrInsertComputed() 方法是 Map 例項上的一個方法,它返回此 Map 中與指定鍵關聯的值。如果鍵不存在,它會使用給定的回撥函式計算一個預設值,並插入一個新條目(鍵和計算出的值),然後返回這個插入的值。

當預設值計算成本較高,並且您希望避免在實際上不需要時進行計算時,請使用此方法而不是 Map.prototype.getOrInsert()

試一試

const map = new Map([["bar", "foo"]]);
const defaultCreator = (key) => `default for ${key}`;

console.log(map.getOrInsertComputed("bar", defaultCreator));
// Expected output: "foo"

console.log(map.getOrInsertComputed("baz", defaultCreator));
// Expected output: "default for baz"

語法

js
getOrInsertComputed(key, callback)

引數

key

Map 物件中返回元素的鍵。物件鍵透過 引用 進行比較,而不是透過值。

回撥

一個函式,用於在鍵尚未存在於 Map 物件中時返回要插入並返回的值。該函式將使用以下引數進行呼叫:

key

傳遞給 getOrInsertComputed() 的鍵。  

返回值

Map 物件中指定鍵關聯的值。如果找不到鍵,則插入並返回 callback(key) 的結果。

示例

避免不必要的預設值計算

使用 Map.prototype.getOrInsert() 時,即使預設值不需要,也會每次都計算。而使用 getOrInsertComputed(),預設值僅在必要時計算。

js
const map = new Map([["bar", "foo"]]);
const defaultCreator = (key) => {
  console.log(`Creating default for ${key}`);
  return `default for ${key}`;
};

map.getOrInsert("bar", defaultCreator("bar")); // Logs "Creating default for bar"
map.getOrInsertComputed("bar", defaultCreator); // No log

規範

規範
Upsert (更新或插入)
# sec-map.prototype.getOrInsertComputed

瀏覽器相容性

另見