WeakMap.prototype.getOrInsert()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

WeakMap 实例的 getOrInsert() 方法会返回此 WeakMap 中与指定键对应的。如果键不存在,它会使用给定的默认值插入一个新条目,并返回插入的值。

如果默认值的计算成本很高,请考虑改用 WeakMap.prototype.getOrInsertComputed(),它接受一个回调函数,仅在实际需要时计算默认值。

试一试

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

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

语法

js
getOrInsert(key, defaultValue)

参数

key

要从 WeakMap 对象返回的值的键。必须是对象或 未注册的 Symbol。对象键通过 引用 进行比较,而不是通过值。

defaultValue

如果键尚不存在于 WeakMap 对象中,则要插入并返回的值。

返回值

WeakMap 对象中与指定键关联的值。如果找不到键,则返回 undefined

异常

TypeError

如果 key 不是对象或 未注册的 Symbol,则会抛出错误。

示例

使用 getOrInsert()

js
const wm = new WeakMap();
const obj = {};

console.log(wm.get(obj)); // undefined
console.log(wm.getOrInsert(obj, "default")); // "default"
console.log(wm.get(obj)); // "default"
console.log(wm.getOrInsert(obj, "another default")); // "default"

规范

规范
Upsert (更新或插入)
# sec-weakmap.prototype.getOrInsert

浏览器兼容性

另见