简体   繁体   English

Javascript中的索引数组名称

[英]Indexed Array Names in Javascript

I have set of arrays named "list0 ........ through to list7" explicitly defined. 我已经明确定义了一组名为“ list0 ........到list7”的数组。 I want to make each of these arrays an element in an existing array (so I have a 2D array of these defined arrays) 我想使这些数组中的每一个成为现有数组中的一个元素(所以我拥有这些已定义数组的2D数组)

how do I reference each 'list' array in a 'for' loop? 如何在“ for”循环中引用每个“列表”数组?

for example: 例如:

var matrix1 = new Array();

function makeMatrix1(){

    for(row=0; row<8; row++)
    {       

        matrix1[row] = list[row]//put each 'list' array into matrix1 as an element

    }

The above syntax does not work, obviously. 显然,以上语法不起作用。

What about: 关于什么:

var matrix1 = [list0, list1, list2, list3, list4, list5, list6, list7];

It's not a for loop, but it seems simple enough (perhaps simpler than a for loop) and gets the job done. 它不是for循环,但看起来很简单(也许比for循环更简单)并且可以完成工作。 The alternative, I think, would be to use an eval (which I personally try avoid at almost any cost). 我认为,替代方法是使用eval (我个人几乎不惜一切代价避免这样做)。

var matrix1 = [];
for (row = 0; row < 8; row++) {
    matrix1.push(eval("list" + row));
}

You can do something like this 你可以做这样的事情

   var myTwoDimArray = [listo,........,list7];  

now print by 现在打印

   alert(myTwoDimArray[0][0]);  

Hope this helps. 希望这可以帮助。

list0, list1, list2 etc is already numbered as an array structure. list0,list1,list2等已被编号为数组结构。 How about 怎么样

list=new Array();
list[0]=["a","b","c"];
list[1]=["d","e"];
list[2]=["f","g","h","j"];
etc

then you already have your matrix structure. 那么您已经有了矩阵结构。 So as you are already defining rows explicitly you could do 因此,当您已经明确定义行时,您可以执行

matrix=new Array();
matrix[0]=["a","b","c"];
matrix[1]=["d","e"];
matrix[2]=["f","g","h","j"];
etc

matrix[1][1] would give "e" matrix[2][3] would give "j" etc 矩阵[1] [1]将给出“ e”矩阵[2] [3]将给出“ j”等

Of course you could just do 当然可以

matrix=[
   ["a","b","c"],
   ["d","e"],
   ["f","g","h","j"],
.....
.....
and so on for each of the 8 rows

]

for same result 对于相同的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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