【问题标题】:Mutable arrays as values in ES6 Map可变数组作为 ES6 Map 中的值
【发布时间】:2016-02-04 17:22:06
【问题描述】:

使用数组(可能经常被推送和拼接)作为 ES6 Map 中的值是否有意义,还是应该坚持使用普通关联数组?

例如,类似于以下节点服务器代码的代码,它将跟踪哪些用户已经下载了特定文件

// initialisation
var map = new Map();
map.set ("foo.png",[]);

// push a new user id to array associated with hashString 
function userHasFile(filename,userId) {

    // retrieve array of all userIds that have downloaded the file
    var users = map.get(filename);

    // delete the map reference since we are going to update it
    map.delete(filename);

    // push the new userId to the array of users that have downloaded file
    users.push(userId);

    // update the Map key to the new array
    map.set(filename,users);
}

// example usage
userHasFile("foo.png","user1");
userHasFile("foo.png","user2");

我是 ES6 新手,Map API 的简单性对我很有吸引力,所以我想知道这种方法与使用标准关联数组相比是否有任何好处\缺点(例如性能、内存、GC 等) .

【问题讨论】:

    标签: javascript arrays ecmascript-6


    【解决方案1】:

    绝对的。

    拥有一个键列表存储是一种足够有用的模式,它是the data types in Redis 之一。

    在 Map 中保留一个数组是一件完全合法且有用的事情。这是存储符合某些条件的对象列表的好方法,并且在 JavaScript(和其他使用引用的语言)中特别有效。地图实际上并不保存数组的副本,只是对它的引用,因此您可以从地图外部修改数组,地图将在不知道或调整大小的情况下更新。

    但是,如果有意义,您应该小心使用更多功能模式。如果您有传入的项目,您可能希望将它们流式传输到 map/reduce(使用 reduce 按键对它们进行分组),而不是保留 map 并修改底层数组。您在这里依赖参考和副作用。

    如果你想阻止数组在某个时候被更新,你可以用不可变数组替换它们,使用像immutable.js这样的库。

    如果您在服务器中工作,例如,您需要记录传入的请求,但您不知道它们何时到达(statsd 所做的那种缓存和刷新),那么映射是有意义的:

    let responses = new Map();
    
    server.on('request', function (url, responseTime) {
      if (!responses.has(url)) {
        responses.set(url, []);
      }
    
      const times = responses.get(url);
      times.push(responseTime);
    });
    
    const flushTimer = setInterval(function () {
      stats.write(responses);
      responses = new Map();
    }, 10*1000);
    

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2015-12-16
      相关资源
      最近更新 更多