Map.prototype.get()
Map 例項的 get() 方法返回此 Map 中與指定鍵對應的值,如果鍵不存在,則返回 undefined。物件值將返回原始儲存的相同引用,而不是副本,因此對返回物件的修改將反映在持有該引用的任何地方,包括 Map 內部。
試一試
const map = new Map();
map.set("bar", "foo");
console.log(map.get("bar"));
// Expected output: "foo"
console.log(map.get("baz"));
// Expected output: undefined
語法
js
get(key)
引數
返回值
Map 物件中與指定鍵關聯的值。如果找不到鍵,則返回 undefined。
示例
使用 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() 檢索物件的引用
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"]
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-map.prototype.get |
瀏覽器相容性
載入中…