了解Javascript中的嵌套数组 [英] understanding nested arrays in Javascript
问题描述
我想用Javascript创建一个嵌套数组,但不能做我想做的事情,我不知道是否有可能.这是我要创建哪种数组的示例:
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'];
然后,我想为每个id添加新数组,以使id值保持不变.为什么?因为我想使用indexOf方法找出具有子数组ID的主数组的元素索引.像这样:
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 ;
如果有某种方法可以知道,那真是太好了,但是如果不是这样的话,我想我将使用2个数组,一个将保存子数组,另一个将保存ids
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.
推荐答案
也许你想做
array[0] = {par1: 'somevalue', par2: someother};
array[1] = {par1: 'anotehrone', par2: stillanother};
这会将javascript对象数组设置为元素,此处用作关联数组.它们使您可以通过按键设置或获取元素:
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
但是,如果您还想让array[0]
返回不是通用对象而是字符串的内容,那么您可能不希望使用javascript.这种语言就不能那样工作.
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.
这篇关于了解Javascript中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!