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

Map.prototype.getOrInsertComputed()

· 52CE 我爱测

The **`getOrInsertComputed()`** 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 default value computed from a given callback, and returns the inserted value.

The getOrInsertComputed() 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 default value computed from a given callback, and returns the inserted value.

Use this method instead of Map.prototype.getOrInsert() when the default value is expensive to compute, and you want to avoid computing it unless it's actually needed.

JavaScript Demo: Map.prototype.getOrInsertComputed()

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"

Syntax

getOrInsertComputed(key, callback)

Parameters

  • key
    • : The key of the element to return from the Map object. Object keys are compared by reference, not by value.
  • callback
    • : A function that returns the value to insert and return if the key is not already present in the Map object. The function is called with the following argument:
      • key
        • : The same key that was passed to getOrInsertComputed().

Return value

The value associated with the specified key in the Map object. If the key can't be found, the result of callback(key) is inserted and returned.

Exceptions

  • TypeError
    • : Thrown if callback isn't callable.

Examples

Avoiding unnecessary default computation

When using Map.prototype.getOrInsert(), the default value is computed every time, even if it is not needed. With getOrInsertComputed(), the default value is only computed when necessary.

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

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

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

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