[ES6] When should use Map instead of Object

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!
原文地址:https://www.cnblogs.com/Answer1215/p/5129036.html