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

浏览器兼容性

另见