首页 > 其他 > 详细

[ES6] When should use Map instead of Object

时间:2016-01-14 06:15:12      阅读:200      评论:0      收藏:0      [点我收藏+]

Use Maps when keys are unknown until runtime:

Map:

let recentPosts = new Map();

createPost( newPost, (data)=>{

    // Key unknown until runtime, so use Map
   recentPosts.set(data.author, data.message);
});

 

Object:

const POST_PRE_PAGE=15;

// Keys are previously defined, so use object!
let userSettings = {
   perPage: POST_PRE_PAGE,
   showRead: true
}

 

Use Map when types are the same:

Map:

let recentPosts = new Map();

createPost(newPost, (data) => {
   recentPost.set(data.author, data.message);
});

// ...somehwere else in the code
socket.on(‘new post‘, function(data){
   recentPosts.set(data.author, data.message) 
})

Notice in the code, both places keys: ‘data.author‘ are the same type and data: ‘data.message‘ are also the same type.

 

Object:

const POST_PRE_PAGE = 15;

let userSettings = {
   prePage: POST_PRE_PAGE,
   showRead: true
};
// Some values are numeric, others are boolean, so use Object!

 

[ES6] When should use Map instead of Object

原文:http://www.cnblogs.com/Answer1215/p/5129036.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!