Click to See Complete Forum and Search --> : Two-dimensional arrays


Thomas2
12-09-2003, 12:13 PM
I am having problems with using two-dimensional arrays. Assigning values to it apparently works OK, but referencing the array later repeats only the values of the last column for each column (if you run the script below, it should print out the same sequence twice, but only the first (from the assignment loop) is correct).

<html>
<body>

<SCRIPT Language="Javascript" type="text/javascript">
<!--
var arr=new Array();

for (i=0; i<=2; i++) {
for (j=0; j<=1; j++) {
arr[i,j]=i+j;
document.write(arr[i,j]);
}
}

document.write(' ');

for (i=0; i<=2; i++) {
for (j=0; j<=1; j++) {
document.write(arr[i,j]);
}
}

//-->
</SCRIPT>


</body>
</html>

TheBearMay
12-09-2003, 12:43 PM
The short answer is that you only have a one dimensional array of two items defined - do a:

document.write(arr.toString());

and you'll see what I'm talking about.

batfink
12-09-2003, 12:58 PM
Try this:

<html>
<body>
<SCRIPT Language="Javascript" type="text/javascript">
<!--
var arr=new Array();
for (i=0; i<=2; i++)
{
arr[i]= new Array();
for (j=0; j<=1; j++)
{
arr[i][j]=i+j;
document.write(arr[i][j]);

}
}
document.write(" ");

for (i=0; i<=2; i++)
{
for (j=0; j<=1; j++)
{
document.write(arr[i][j]);
}
}

//-->
</SCRIPT>
</body>
</html>

TheBearMay
12-09-2003, 01:06 PM
Thanks for following on batfink, I got interupted before I could get back with a more informative post.

Thomas2
12-10-2003, 11:42 AM
Thanks for your help Batfink. I have got my program working now as it should.
I assumed arr[i,j] would be a valid syntax for a two-dimensional array as Javascript did not issue any error message (I found this syntax mentioned in another forum and I am also used to it from other programming languages).