PDA

View Full Version : Need help with generating a 2D array using nested for loops


shivboy
11-16-2002, 05:39 PM
Okay, i've been experimenting dynamically accessing a matrix of layers. Now, i wanted to create an array of the id's of the layers in the matrix. that would mean a two dimensional array. but instead of generating an array, it gives an error " Expected ;" at the line (bold line in the code below) im trying to generate an array with div id's. the layers r arranged like:

*************
*************
*************

and the div id's go like div1_1 where it means div[row]_[column]. so i give this nested for loop construct:


var oTh = new Array();
for (var i = 1; i <= 10; i++)
{
for (var j = 1; j <= 20; j++)
{
eval('oTh["'+i+'"]["'+j+'"]= "div'+i+'_'+j+'"');
}
}


in the <body>, the divs are created like:
<div id="div1_1">
</div>
<div id="div1_2">
</div>
<div id="div1_3">
</div>
<div id="div1_4">
</div>

but it doesnt work. why? please help me with this. any help is appreciated.

thanx,

shivboy

RadarBob
11-16-2002, 08:34 PM
Or nD arrays for that matter.

What you have to do is first create the "inner" array, and then create a second array assigning the whole inner array to an element of the outer array. THEN you can reference the array like you'd expect:


var outerArray = new Array();

for (var i=0; i<10; i++) {
var innerArray = new Array();
for (var j=0; j<20; j++) {
innerArray[i] = whatever
}
outerArray[i] = innerArray;
}

var thing = OuterArray[1][1]; // etc.

jkd
11-16-2002, 09:07 PM
Originally posted by RadarBob
Or nD arrays for that matter.

But that is the definition of multi-dimensional arrays - having an array of arrays.

shivboy
11-17-2002, 06:11 AM
hi jkd,

thanx for the help man! but unfortuantely that didnt work :(. no error but it didnt work.

Roelf
11-17-2002, 06:43 AM
You also have to create the inner array which radarbob mentioned, like:

var oTh = new Array();
for (var i = 1; i <= 10; i++)
{
var oTh[i] = new array();
for (var j = 1; j <= 20; j++)
{
eval('oTh["'+i+'"]["'+j+'"]= "div'+i+'_'+j+'"');
}
}

shivboy
11-17-2002, 05:31 PM
hi Roelf,

thanx for replying dude. i tried the code but it generates a very unlikely error "oTh.21 is null or not an object". why so? i'm not creating any objects using this for loop construct anyway.

thanx again,
shivboy

Roelf
11-17-2002, 07:01 PM
Then try:
var oTh = new Array();
for (var i = 1; i <= 10; i++)
{
var temp = new Array();
oTh[i] = temp;
for (var j = 1; j <= 20; j++)
{
eval('oTh["'+i+'"]["'+j+'"]= "div'+i+'_'+j+'"');
}
} [/B][/QUOTE]

shivboy
11-17-2002, 07:37 PM
hi roelf,

thanx man. IT WORKED! FINALLY ! :):cool: thanx for ur help.

thanx,
shivboy