Reesy to understand Multidimensional arrays you have to understand a few things about the normal arrays. Multidimensional arrays are nothing more than arrays within arrays.
Here is a shorthand way of defining an array :
var numbers = [1, 2, 3, 4]
It is the same as doing this :
var numbers = new Array()
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
numbers[3] = 4
In both examples to get the value at index 2 I would need to write numbers[2] and I would get three. But notice that doing this : [1, 2, 3, 4][2] also gives me three.
You can also have arrays within an array like so :
var numbers = new Array()
numbers[0] = [11, 22, 33, 44]
numbers[1] = [22, 564, 987, 456]
numbers[2] = [3]
numbers[3] = [4, 8]
And the shorthand version would be :
var numbers = [ [11, 22, 33, 44] ,[22, 564, 987, 456], [3], [4, 8] ]
This is a multidimensional array. And to loop through it is actually quite easy. First I will give you an example of how I can get the elements of a normal array :
var numbers = [1, 2, 3, 4]
for (var index = 0; index < numbers.length; index++)
{
document.write("<br> at index : " + index + " the value is " + numbers[index])
}
This would write down on your page :
at index 0 the value is 1
at index 1 the value is 2
at index 2 the value is 3
at index 3 the value is 4
Now if you had a multidimensional array you could also print things out like that :
var numbers = [ [11, 22, 33, 44] ,[22, 564, 987, 456], [3], [4, 8] ];
for (var index = 0; index < numbers.length; index++)
{
document.write("<br> at index : " + index + " the value is " + numbers[index])
}
The result on screen would be :
at index : 0 the value is 11,22,33,44
at index : 1 the value is 22,564,987,456
at index : 2 the value is 3
at index : 3 the value is 4,8
Now if you see the content at each index is actually an array. When an array is printed or alerted javascript transforms it into a string seperating each element by a coma.
Since each element at each index is an array you simply have to nest another for loop and loop through each array at every index :
var numbers = [ [11, 22, 33, 44] ,[22, 564, 987, 456], [3], [4, 8] ];
for (var index = 0; index < numbers.length; index++)
{
for (var innerIndex = 0; innerIndex < numbers[index].length; innerIndex++)
{
document.write("<br> at [index][innerIndex] : [" + index + "][" + innerIndex + "]the value is " + numbers[index][innerIndex])
}
}
at [index][innerIndex] : [0][0]the value is 11
at [index][innerIndex] : [0][1]the value is 22
at [index][innerIndex] : [0][2]the value is 33
at [index][innerIndex] : [0][3]the value is 44
at [index][innerIndex] : [1][0]the value is 22
at [index][innerIndex] : [1][1]the value is 564
at [index][innerIndex] : [1][2]the value is 987
at [index][innerIndex] : [1][3]the value is 456
at [index][innerIndex] : [2][0]the value is 3
at [index][innerIndex] : [3][0]the value is 4
at [index][innerIndex] : [3][1]the value is 8
I hope this clears things out. Gary
Haran