找到你要的答案

Q:how to create a map in javascript with array of values dynamically

Q:如何动态创建与数组JavaScript地图

I have this requirement. Depending on the number of arguments passed in the function, I need to create that many entries in my map. Say I have a function myfunc1(a,b,c) , I need to have a map with the keys as "a","b" and "c" and I can have more than one values for each of the keys. But the problem is that I do not know beforehand, how many values will come for those keys. As and when the values come, I need to add them to the list of values corresponding to the matching key in the map. How do I do this in javascript? I have found static answers like below. But I want to do this dynamically. Can we use the push method ?

var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];

我有这个要求。根据函数中传递的参数的数量,我需要在我的地图中创建许多条目。说我有一个功能myfunc1(A,B,C),我需要一个地图和钥匙为“A”,“B”和“C”,我可以有一个以上的值,每个键。但问题是,我不知道事先,有多少价值来为这些关键。当值到达时,我需要将它们添加到对应于map中匹配键的值的列表中。我如何用JavaScript做这个吗?我找到静态答案如下。但我想这样做动态。我们能用推法吗?

var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];
answer1: 回答1:

I think this is what you are asking. addValueToList will create array/list dynamically if the key is not present in the map.

//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);
}

我想这就是你要问的。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);
}
answer2: 回答2:

You can use the arguments list to populate your object with key corresponding to the strings passed in as arguments. Then you can write another function to populate this map with data.

var createMap = function() {
    var map = {};
    Array.prototype.slice.call(arguments).forEach(function ( arg ) {
        map[arg] = null;
    });
    return map;
}

So createMap('para1', para2', para3') will return an object with 3 keys: para1, para2, para3. All having null as value. You can obviously replace null with a reference to the data you want the key to have, if you want to do it all in one function.

您可以使用参数列表来填充对象,其中的键对应于作为参数传递的字符串。然后,您可以编写另一个函数来填充此映射的数据。

var createMap = function() {
    var map = {};
    Array.prototype.slice.call(arguments).forEach(function ( arg ) {
        map[arg] = null;
    });
    return map;
}

所以创建地图('para1 ',然而,河源”)将返回3个对象:但是,然而,河源。所有有空值。如果你想在一个函数中全部执行,你可以用一个对你想要密钥的数据的引用来代替null。

javascript  node.js  dictionary  functional-programming