使用对象作为ES2015映射键 [英] Using object as ES2015 map key
问题描述
我一直试图掌握ES2015地图的概念,但我不了解的一件事是:
I've been trying to get a hold of ES2015 map concept and one thing I don't understand is the following:
var mapRawObj = new Map();
var rawObj = {j:"I like penguin"};
mapRawObj.set(rawObj,true);
console.log(mapRawObj.get(rawObj)); //this outputs true
mapRawObj.set({j:"I like polar bear"},true);
console.log(mapRawObj.get({j:"I like polar bear"})); //this outputs undefined
第一个有效,第二个无效,我不不知道为什么吗?
The first one works, the second one doesn't, and I don't understand why?
我想当您将对象注册为键时,它是对象本身,而不是对象的名称。这就是为什么在下面的示例中,当您重新分配键对象时,它作为键失败了吗?
I thought when you register object as key, it's the object itself, not the object's name. That's why in the below example when you re-assign the key object, it fails as key?
var obj = { a:"hello ", b:"world "};
var mapObj = new Map();
mapObj.set(obj,true);
obj = {d:34}; //obj is re-assigned
console.log(mapObj.get(obj)); // outputs undefined
推荐答案
具有相同数据的对象不是等于Javascript,即
Objects with the same data are not equal in Javascript, ie
{ hello: 'world'} === { hello: 'world'} // false
第一个示例使用与set和get的键相同的对象,因此该键是相同的: / p>
The first example uses the same object as the key for set and get, so the key is identical:
var obj = { hello: 'world'};
obj === obj // true
但是第二个示例为 get()
,它与用于在地图中设置值的键不同。由于不相同,因此地图没有针对此新键设置任何内容,并返回 undefined
。
But the second example creates a new object for the get()
, which is not identical to the key used to set the value in the map. Since it's not identical, the map doesn't have anything set against this new key and returns undefined
.
甚至尽管新密钥与原始密钥具有完全相同的数据,但是对象内部没有引用相同的数据。
Even though the new key has exactly the same data as the original key, the objects aren't referring to the same data internally.
这篇关于使用对象作为ES2015映射键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!