Different ways for adding key/value pair to a Map in JavaScript

北战南征 提交于 2021-01-29 08:37:45

问题


According to MDN set Method for Map, the only way for adding key/value pair to a map in javascript is a set method. I am wondering what the behavior of a map is when we add a key/value pair with a square bracket like below;

const testMap = new Map();
testMap.set( 1,"firstValue" );
testMap[2] = "secondValue";
console.log( testMap );
console.log( testMap[ 2 ] );
console.log( testMap[ '2' ] );

It seems that we can have both a map and object together! Can somebody explain this to me? I know that Map is a kind of object but this behavior can cause a lot of bugs. Is there any way to prevent this? By the way, if you add a key/value pair with square brackets, then you cannot use get method to retrieve it.


回答1:


This is a special situation.

Maps are a special case that contain an entriesarray internally. When you use the array notation, your setting key/value pairs outside this entries array.

When you use the set or get method you are actually using the internal entries array used by the map code.

The example above, essentially creates a Map object that is using the internal entries array. However, setting the second object using the array notation, means you are adding another entry/property but not in the Entries array.

Also, these values are completely different. Do note though that these two data structures don't collide. So testMap.get(2) is not the same variable as testMap[2].




回答2:


No your example doesn't work as expected, when you use brackets, you are setting a property on the testMap object not setting an entry. You can confirm that by iterating over your map using the forEach method for example.

const testMap = new Map();
testMap.set(1, "firstValue");
testMap[2] = "secondValue";

testMap.forEach(x => console.log(x));

As you can see, there is no secondValue on the console, that is, there is no mapped entry with that value. Therefore, it wasn't added to the map what so ever.

And definetly, testMap.set(1, "firstValue"); is not equivalent to testMap[1] = "firstValue"; the only reason your are allowed to do that is because javascript permit you to add property to living objects but it is not added to the map entries.

Ref.: MDN Map



来源:https://stackoverflow.com/questions/52184618/different-ways-for-adding-key-value-pair-to-a-map-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!