如何为 JavaScript 字典创建和添加值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20883113/
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 and add values to a JavaScript Dictionary
提问by BeingNerd
I'm trying to create a Dictionary with a key and a value list pair. I'm able to create a dictionary for a key value pair but I need to insert a list of Items as value for a key value. Here is my approach:
我正在尝试创建一个带有键和值列表对的字典。我能够为键值对创建字典,但我需要插入一个项目列表作为键值的值。这是我的方法:
keys = ['A', 'B', 'C'];
Elements Corresponding to 'A' : 'apple'
Elements Corresponding to 'B' : 'ball', 'balloon','bear'
Elements Corresponding to 'C' : 'cat','cow'
and my result should be like:
我的结果应该是这样的:
{ key:'A' value:['apple'], key:'B' value:['ball',balloon','bear'], Key:C' value:['cat','cow']}
Here is just a sample data, I will get data dynamically from a table.Please help me out.Thanks In advance.
这里只是一个示例数据,我将从表中动态获取数据。请帮助我。在此先感谢。
采纳答案by Mykola Prymak
This code can add a new key-value pair into some dictonary like object.
这段代码可以将一个新的键值对添加到一些像对象这样的字典中。
var dictionary= {};
function insertIntoDic(key, value) {
// If key is not initialized or some bad structure
if (!dictionary[key] || !(dictionary[key] instanceof Array)) {
dictionary[key] = [];
}
// All arguments, exept first push as valuses to the dictonary
dictionary[key] = dictionary[key].concat(Array.prototype.slice.call(arguments, 1));
return dictionary;
}
回答by Rajaprabhu Aravindasamy
回答by Hans
Here's an example:
下面是一个例子:
/* Define dictionary */
var dict = {};
/* Define keys */
var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* Assign array as value for each key */
for (var n = 0; n < keys.length; n++) {
dict[keys[n]] = [];
}
/* Make up a bunch of words */
var words = ["apple", "ball", "balloon", "bear", "cat", "cow"];
/* Append these words to the dictionary according to their first letter */
for (n = 0; n < words.length; n++) {
dict[words[n][0].toUpperCase()].push(words[n]);
}