[英]How to define a jagged associative array in javascript?
I'm trying to define an array which works this way: 我试图定义一个这样工作的数组:
myArray[0] = 'Volkswagen'
myArray[0][0] = 'Crossfox'
myArray[1] = 'Ford'
myArray[1][0] = 'Focus'
I can do by hand but of course it's not the way to do it. 我可以手工做,但是当然不是这样做的。 I have a simple array with this: 我有一个简单的数组:
arrayVolks = ['Crossfox', 'Up', 'Golf'];
arrayVolks[name] = 'Volkswagen';
My problem is that I don't know how to create the first array with the index with the name of the array and then add the array . 我的问题是我不知道如何用带有数组名称的索引创建第一个数组 , 然后添加该数组 。
I was thinking on some way like this: 我在想这样的方式:
var myArray = [ arrayVolks[name]: {arrayVolks} ]
(The code immediately over it's more like a pseudo code than actual javascript) (紧随其后的代码更像是伪代码,而不是实际的javascript)
Is it possible? 可能吗?
Thank you in regards 谢谢你的问候
you can't create array like this in javascript: 您无法在javascript中创建这样的数组:
myArray[0] = 'Volkswagen'
myArray[0][0] = 'Crossfox'
myArray[1] = 'Ford'
myArray[1][0] = 'Focus'
how about using Object
instead? 改用Object
怎么样?
var obj = {};
obj['Volkswagen'] = ['Crossfox', 'Up', 'Golf'];
obj['Ford'] = ['Focus'];
// get all brands
console.log(Object.keys(obj));
// print all "Volkswagen"
console.log(obj['Volkswagen']);
console.log(obj.Volskwagen);
A jagged array is an array of arrays. 锯齿状数组是数组的数组。
By doing myArray[0] = 'Volkswagen'
you set the first element of the root array to a string so you are violating the structure already. 通过执行myArray[0] = 'Volkswagen'
您将根数组的第一个元素设置为字符串,因此您已经违反了结构。
An alternate data structure would probably be better, but if you wish to have a jagged array you may define a structure where the first element of each nested array is the make while the other elements will be the models. 备用数据结构可能会更好,但是如果您希望有一个锯齿状的数组,则可以定义一个结构,其中每个嵌套数组的第一个元素是make,而其他元素将是模型。
var cars = [ ['Volkswagen', 'Crossfox'], ['Ford', 'Focus'] ]; console.log(cars[0][0]); //Volkswagen console.log(cars[0][1]); //Crossfox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.