Gor*_*oro 27 javascript web-applications
我想像这样定义一个关联数组
var theVar = [
{ "100", [0, 1, 2] },
{ "101", [3, 4, 5] }
]
Run Code Online (Sandbox Code Playgroud)
基本上我希望能够通过指定自定义索引来访问三个数字的数组.
但是,无论我尝试什么,我都无法使其发挥作用.
我知道我可以将它定义为:
theVar["100"] = [0, 1, 2];
theVar["101"] = [1, 2, 3];
Run Code Online (Sandbox Code Playgroud)
但我将其设置在其他地方,我宁愿能够在一个声明中设置它.
Mva*_*est 34
theVar = {
"100": [0, 1, 2],
"101": [3, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)
可能会做的伎俩.然后,您可以使用theVar["101"](或theVar[101]就此而言)进行访问.
(因为var它也是JavaScript中的关键字,将其用作变量名称很可能会导致问题.)
看看JSON语法,我认为它可以激发您的数据结构的构建,使其灵活,正确和复杂.
此页面包含大量有助于您的信息和示例.
比如看看这个:
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
Run Code Online (Sandbox Code Playgroud)