Javascript 如何在javascript中动态创建具有值数组的地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33020554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create a map in javascript with array of values dynamically
提问by Zack
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 ?
我有这个要求。根据函数中传递的参数数量,我需要在我的地图中创建那么多条目。假设我有一个函数 myfunc1(a,b,c) ,我需要有一个键为“a”、“b”和“c”的映射,并且每个键可以有多个值。但问题是我事先不知道这些键会有多少个值。当值出现时,我需要将它们添加到与映射中匹配键对应的值列表中。我如何在 javascript 中做到这一点?我找到了如下静态答案。但我想动态地做到这一点。我们可以使用推送方法吗?
var map = {};
map["country1"] = ["state1", "state2"];
map["country2"] = ["state1", "state2"];
回答by rajuGT
I think this is what you are asking. addValueToList
will create array/list dynamically if the key is not present in the map.
我想这就是你要问的。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);
}
回答by Shilly
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.
所以createMap('para1', para2', para3')
将返回一个带有 3 个键的对象:para1、para2、para3。都具有 null 作为值。如果您想在一个函数中完成所有操作,您显然可以将 null 替换为对您希望密钥拥有的数据的引用。