博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[ES6] Objects vs Maps
阅读量:6469 次
发布时间:2019-06-23

本文共 1064 字,大约阅读时间需要 3 分钟。

Map is really useful when you want to use object as a key to set vaule, in ES5, you cannot really use object as a key:

 

var user1 = {  name: "Wan",  age: 25};var user2 = {  name: "Zhen",  age: 27};var users = {};users[user1] = 5;users[user2] = 10;console.log(users);/**[object Object] {  [object Object]: 10}**/

 

As you can see, the output is always 10. It means the last value will overwrite the previous value.

The reason for that is because in Javascript, when you use Array syntax to assign value, the 'key' is always 'string'.

 

So if you use object 'user1', Javascript engine actually read it as 

"[object Object]"

 

In other words, no matter what object you give, the 'users' array has only one value:

console.log(Object.keys(users));  // ["[object Object]"]

 

-------------------------------------------------

 

Map in ES6 can help to solve the problem:

var user1 = {  name: "Wan",  age: 25};var user2 = {  name: "Zhen",  age: 27};var users = new Map();users.set(user1, 5);users.set(user2, 10);console.log(users.get(user1));  // 5console.log(users.get(user2));  // 10

 

转载地址:http://nkcko.baihongyu.com/

你可能感兴趣的文章
学生选课系统数据存文件
查看>>
git bash 风格调整
查看>>
linux 脚本map,Linux Shell Map的用法详解
查看>>
linux操作系统加固软件,系统安全:教你Linux操作系统的安全加固
查看>>
linux中yum源安装dhcp,24.Linux系统下动态网络源部署方法(dhcpd)
查看>>
C#技术------垃圾回收机制(GC)
查看>>
漫谈并发编程(三):共享受限资源
查看>>
【转】github如何删除一个仓库
查看>>
状态模式
查看>>
HDOJ-1010 Tempter of the Bone
查看>>
JavaNIO基础02-缓存区基础
查看>>
日本开设无人机专业,打造无人机“人才市场”
查看>>
190行代码实现mvvm模式
查看>>
PXE部署实例
查看>>
cobbler初探------实现自动安装centos6.4
查看>>
兼容几乎所有浏览器的透明背景效果
查看>>
Go语言4
查看>>
jeesite 框架搭建与配置
查看>>
Adb移植(一)简单分析
查看>>
Linux VNC server的安装及简单配置使用
查看>>