简体   繁体   中英

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)

Is it possible?

Thank you in regards

you can't create array like this in javascript:

myArray[0] = 'Volkswagen'
myArray[0][0] = 'Crossfox'
myArray[1] = 'Ford'
myArray[1][0] = 'Focus'

how about using Object instead?

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.

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.

 var cars = [ ['Volkswagen', 'Crossfox'], ['Ford', 'Focus'] ]; console.log(cars[0][0]); //Volkswagen console.log(cars[0][1]); //Crossfox 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM