在 JavaScript 中将键/值对添加到 Map 的不同方法 [英] Different ways for adding key/value pair to a Map in JavaScript
问题描述
根据 MDN
上面的示例本质上创建了一个使用内部 entries
数组的 Map 对象.但是,使用数组表示法设置第二个对象意味着您要添加另一个条目/属性,但不在 Entries 数组中.
此外,这些值完全不同.请注意,这两个数据结构不会发生冲突.所以 testMap.get(2) 和 testMap[2] 不是同一个变量.
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.
This is a special situation.
Maps are a special case that contain an entries
array 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].
这篇关于在 JavaScript 中将键/值对添加到 Map 的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!