如何动态地用javascript数组创建一个地图 [英] how to create a map in javascript with array of values dynamically
问题描述
我有这个要求。根据函数中传递的参数数量,我需要在地图中创建许多条目。假设我有一个函数myfunc1(a,b,c),我需要一个带有a,b和c键的映射,并且每个键可以有多个值。但问题是,我不知道,这些键有多少值。当值到来时,我需要将它们添加到与映射中匹配键相对应的值列表中。我如何在JavaScript中做到这一点?我找到如下的静态答案。但我想动态地做到这一点。我们可以使用push方法吗?
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"];
推荐答案
我想这就是您要求的。 addValueToList
将在地图中不存在该键时动态创建数组/列表。
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);
}
这篇关于如何动态地用javascript数组创建一个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!