大网数据广告活动
Web 标准与前端开发

Map.prototype.getOrInsert()

· 52CE 我爱测

The **`getOrInsert()`** method of Map instances returns the value corresponding to the specified key in this `Map`. If the key is not present, it inserts a new entry with the key and a given default value, and returns the inserted value.

The getOrInsert() method of Map instances returns the value corresponding to the specified key in this Map. If the key is not present, it inserts a new entry with the key and a given default value, and returns the inserted value.

If the computation of the default value is expensive, consider using Map.prototype.getOrInsertComputed() instead, which takes a callback to compute the default value only if it's actually needed.

JavaScript Demo: Map.prototype.getOrInsert()

const map = new Map([["bar", "foo"]]);
console.log(map.getOrInsert("bar", "default"));
// Expected output: "foo"

console.log(map.getOrInsert("baz", "default"));
// Expected output: "default"

Syntax

getOrInsert(key, defaultValue)

Parameters

  • key
    • : The key of the value to return from the Map object. Object keys are compared by reference, not by value.
  • defaultValue
    • : The value to insert and return if the key is not already present in the Map object.

Return value

The value associated with the specified key in the Map object. If the key can't be found, defaultValue is inserted and returned.

Description

The getOrInsert() method is equivalent to the following:

if (map.has(key)) {
  return map.get(key);
}
map.set(key, defaultValue);
return defaultValue;

It is also similar to the following pattern (which is slightly less reliable if null or undefined are valid values in your map):

map.set(key, map.get(key) ?? defaultValue);

Examples

Multimap

In a map where each key is mapped to an array of values, you can use getOrInsert() to ensure that the array exists for a given key before attempting to push a new value to the array.

map.getOrInsert(key, []).push(value);

Applying default values

You can use getOrInsert() to ensure that a key exists in a map, even if you currently don't need its value. This is usually to normalize user input.

Imagine you have a map of user preferences, and you want to ensure that a certain preference is always set to a default value if the user hasn't specified it:

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");

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。