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;

它也类似于以下模式(如果 nullundefined 是映射中的有效值,则此模式的可靠性稍差)

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

浏览器兼容性

另见