zoukankan      html  css  js  c++  java
  • [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!
  • 相关阅读:
    hihocoder 1038
    hihocoder 1039
    poj 2774
    bzoj 4690&&4602
    poj 2417
    STL
    poj 1026
    poj 1064
    poj 1861(prim)
    poj 1129
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5129036.html
Copyright © 2011-2022 走看看