Javascript 定义数组的关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2925025/
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
Define associative array of arrays
提问by Goro
I want to define an associative array like this
我想定义一个这样的关联数组
var theVar = [
{ "100", [0, 1, 2] },
{ "101", [3, 4, 5] }
]
Essentially I want to be able to access an array of three numbers by specifying the custom index.
本质上,我希望能够通过指定自定义索引来访问三个数字的数组。
However, no matter what I try I cannot make it work.
但是,无论我尝试什么,我都无法让它发挥作用。
I know I can define it as:
我知道我可以将其定义为:
theVar["100"] = [0, 1, 2];
theVar["101"] = [1, 2, 3];
But I am setting this somewhere else and I'd prefer to be able to set it in a single statement.
但是我将它设置在其他地方,我希望能够在单个语句中设置它。
回答by MvanGeest
theVar = {
"100": [0, 1, 2],
"101": [3, 4, 5]
}
might do the trick. You can then access using theVar["101"](or theVar[101]for that matter).
可能会起作用。然后您可以访问 using theVar["101"](或theVar[101]就此而言)。
(As varis also a keywordin JavaScript, using it as a variable name is very likely to cause problems.)
(asvar也是JavaScript 中的关键字,将其用作变量名很可能会导致问题。)
回答by microspino
Have a look at the JSONsyntax, I think It could inspire the building of your data structures in a way that will be flexible, correct and complex as you want.
看看JSON语法,我认为它可以激发您构建数据结构的灵感,这种方式将根据您的需要灵活、正确和复杂。
Thispage has a lot of information and example that are helpful for you.
这个页面有很多对你有帮助的信息和例子。
For instance look at this:
例如看看这个:
var employees = { "accounting" : [ // accounting is an array in employees.
{ "firstName" : "John", // First element
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary", // Second Element
"lastName" : "Smith",
"age" : 32 }
], // End "accounting" array.
"sales" : [ // Sales is another array in employees.
{ "firstName" : "Sally", // First Element
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim", // Second Element
"lastName" : "Galley",
"age" : 41 }
] // End "sales" Array.
} // End Employees

