Map.prototype.get()

Map 实例的 get() 方法返回此映射中的指定元素。如果与提供的键关联的值是一个对象,那么你将获得对该对象的引用,并且对该对象所做的任何更改都将在 Map 对象内有效地修改它。

¥The get() method of Map instances returns a specified element from this map. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.

Try it

语法

¥Syntax

js
get(key)

参数

¥Parameters

key

Map 对象返回的元素的键。

返回值

¥Return value

与指定键关联的元素,如果在 Map 对象中找不到该键,则为 undefined

¥The element associated with the specified key, or undefined if the key can't be found in the Map object.

示例

¥Examples

使用 get()

¥Using get()

js
const myMap = new Map();
myMap.set("bar", "foo");

console.log(myMap.get("bar")); // Returns "foo"
console.log(myMap.get("baz")); // Returns undefined

使用 get() 检索对象的引用

¥Using get() to retrieve a reference to an object

js
const arr = [];
const myMap = new Map();
myMap.set("bar", arr);

myMap.get("bar").push("foo");

console.log(arr); // ["foo"]
console.log(myMap.get("bar")); // ["foo"]

请注意,持有原始对象引用的映射实际上意味着该对象无法被垃圾收集,这可能会导致意外的内存问题。如果你希望存储在地图中的对象具有与原始对象相同的生命周期,请考虑使用 WeakMap

¥Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a WeakMap.

规范

Specification
ECMAScript Language Specification
# sec-map.prototype.get

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看