简体   繁体   English

映射获取对象键返回未定义

[英]map get object key return undefined

in map we can store any kind of data as a key, so why I cannot get the value of key object using get ?在地图中,我们可以将任何类型的数据存储为键,那么为什么我不能使用 get 获取键对象的值呢?

let map = new Map()
map.set('name', 'str')
map.set(1, 'num')
map.set({country: 'Abuddin'}, 'Tyrant')

so now using map.get(key), gets all values except the object所以现在使用 map.get(key),获取除对象之外的所有值

map.get('name')
"str"

map.get(1)
"num"

map.get({country: 'Abuddin'})
undefined

shouldn't map.get({country: 'Abuddin'}) get Tyrant?不应该 map.get({country: 'Abuddin'}) 得到 Tyrant 吗?

You need the same object reference, not a new object.您需要相同的对象引用,而不是新对象。

 let map = new Map(), object = { country: 'Abuddin' }; map.set('name', 'str') map.set(1, 'num') map.set(object, 'Tyrant') console.log(map.get('name')); console.log(map.get(1)); console.log(map.get(object));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM