Map.prototype.get()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
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
语法
参数
返回值
示例
使用 get()
使用 get() 检索对象的引用
¥Using get() to retrieve a reference to an object
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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also