在 JavaScript 中将键/值对添加到 Map 的不同方法 [英] Different ways for adding key/value pair to a Map in JavaScript

查看:49
本文介绍了在 JavaScript 中将键/值对添加到 Map 的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 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 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].

这篇关于在 JavaScript 中将键/值对添加到 Map 的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆