Creating a custom two-dimensional Array
Before we switch dimensions, lets first quickly review how to create "normal" arrays, and take it from there:
var myarray=new Array(3)
The above creates an array with 3 "storage compartments". Hopefully, this is old stuff to you. Graphically, it is represented as such:
A two-dimensional array is created simply by building on a "normal" array. Constructing a two-dimensional array requires that we declare another array on top of EACH of the "stems" (myarray, myarray...).
Creating a two dimensional array
To start things off, lets first illustrate graphically how a two dimensional array is represented:
As you can see, to manually add a dimension to an array, what we need to do is declare a new array on top of each individual array "stem". The translation of this idea to actual codes, as you will see, is actually very simple:
var myarray=new Array(3) for (i=0; i <3; i++) myarray[i]=new Array(3)
Is this simple or what? Well, it is. The key here is the for loop. By using a for loop, we incremented through the entire original array, declaring a new array at each "stop".
To access and store values into this "demented" array, just use double brackets:
myarray="Compaq 486" myarray="Compaq 586" myarray="Compaq 686" myarray="Dell 486" myarray="Dell 586" myarray="Dell 686" myarray="IBM 486" myarray="IBM 586" myarray="IBM 686"
The trickest part of a two dimensional array may be keeping track of all the storage compartments in the array!
The two dimensional array above has 9 "storage compartments" (3*3).
Continuing on with our discussion, lets create a two dimensional array with 15 storage compartments:
var myarray=new Array(3) for (i=0; i <3; i++) myarray[i]=new Array(5)
If you know your multiplication, you know how to create arrays with any number of storage compartments!
Before we go any further, its appropriate to first discuss just when two dimensional arrays should be used over exiting variable declaration methods. A two dimensional array has a structure of a "tree", where multiple "sub variables" exist within a single "main variable":
"Compaq" here is the main variable that bonds together the sub variables (486,568 etc). You should use a two dimensional array only when you have a situation like the above, where sub grouping of a main variable is necessary.