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!
  • 相关阅读:
    Python_FTP通讯软件
    Python_NAT
    Python_跟随目标主机IP变换
    Python_网络攻击之端口
    spring
    Java多线程总结之线程安全队列Queue
    队列
    路径
    事务的概念
    GBK,UTF-8,和ISO8859-1之间的编码与解码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5129036.html
Copyright © 2011-2022 走看看