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!
  • 相关阅读:
    Data Security---->Control Access to the Organization
    Data Modeling
    Slaesforce Paltform Development Basic
    Customize your Chatter Experience.
    wamp自定义网站根目录及多站点配置
    1053-1055
    1046-1052
    1044-1045
    HDOJ 1038-1043
    HDOJ 1031-1037
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5129036.html
Copyright © 2011-2022 走看看