如何动态地在javascript中创建具有值数组的地图

Zac*_*ack 5 javascript dictionary functional-programming node.js

我有这个要求.根据函数中传递的参数数量,我需要在地图中创建许多条目.假设我有一个函数myfunc1(a,b,c),我需要一个带有键的地图,如"a","b"和"c",我可以为每个键设置多个值.但问题是我事先不知道,这些键会有多少值.当值到达时,我需要将它们添加到与映射中的匹配键对应的值列表中.我如何在javascript中执行此操作?我找到了如下的静态答案.但我想动态地这样做.我们可以使用推送方法吗?

var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];
Run Code Online (Sandbox Code Playgroud)

raj*_*uGT 9

我想这就是你要问的.addValueToList如果地图中没有该键,将动态创建数组/列表.

//initially create the map without any key
var map = {};

function addValueToList(key, value) {
    //if the list is already created for the "key", then uses it
    //else creates new list for the "key" to store multiple values in it.
    map[key] = map[key] || [];
    map[key].push(value);
}
Run Code Online (Sandbox Code Playgroud)