问题
I want to create a nested array in Javascript but can't do the thing what I want, I don't know if it is even possible. Here is an example of what kind of array I want to create:
var array = ['id1', 'id2', 'id3', 'id4'];
Then I want to add new array for each id such way that id values stayed the same. Why? because I want to use indexOf method to find out the element index of main array with sub array id. Something like this:
array[0]['par1'] should return the value of parameter1
array[0]['par2'] should return the value of parameter2
...
array[0] should return "id1" because
alert(array.indexOf("id1")) must return 0 ;
If there is some way of doing it, that would be great to know, but if it is not than I think I will use 2 arrays, one will hold sub arrays and another the ids
sorry for my bad English, I tried my best to explain my needs.
回答1:
Maybe you want to do
array[0] = {par1: 'somevalue', par2: someother};
array[1] = {par1: 'anotehrone', par2: stillanother};
This sets as elements of you array javascript objects, here used as associative arrays. They enable you to set or get elements by key :
array[0]['par1'] = 'new value'; // write
var newval = array[0]['par1']; // read
But if you also want to have array[0]
returning something that's not a generic object but a string... then you probably don't want javascript. This language just doesn't work like that.
来源:https://stackoverflow.com/questions/12374480/understanding-nested-arrays-in-javascript