understanding nested arrays in Javascript

£可爱£侵袭症+ 提交于 2019-12-25 03:00:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!