javascript 如何使用 Node.JS 在哈希表中为每个键存储多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19149496/
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 can I store multiple values per key in a hash table using Node.JS?
提问by Zach Lucas
In javascript, I have a hash map of key value pairs like:
在 javascript 中,我有一个键值对的哈希映射,例如:
"team", "aemt"
"meat", "aemt"
"car", "acr"
And I want to store all of the matching values with the length of the string like this:
我想用字符串的长度存储所有匹配的值,如下所示:
{4, {"team","meat"}}
{3, {"car"}
How would I accomplish this?
我将如何做到这一点?
回答by Bergi
Dividing your sets by length should not be necessary, the hashing algorithm should be able to take care of that itself. It would only be advisable if you're going to sort your words by length.
不需要按长度划分你的集合,散列算法应该能够自己处理。仅当您要按长度对单词进行排序时才可取。
store multiple values per key in a hash table
在哈希表中为每个键存储多个值
You cannot. However, you can store an array of strings for each key.
你不能。但是,您可以为每个键存储一个字符串数组。
var words = ["team", "meat", "car"],
map = {};
for (var i=0; i<words.length; i++) {
var key = words[i].toLowercase().split('').sort().join('');
if (key in map)
map[key].push(words[i]);
else
map[key] = [ words[i] ];
}