by Cory Rauch 2008-09-01 Category: JavaScript
JavaScript does not have native support for multidimensional arrays but using this technique you can create something similar.
JavaScript has built in support for single dimension arrays. You can simply define one by creating a new Array object.
var myArray = new Array();
myArray[0] = "Some Text";
var anotherArray = new Array("Some Text");
In the above code we define a new array and assign the value "Some Text" to the first entry of the array. In the second example, I showed how you can create an array and assign a value to the first entry all in one line.
ReferencesJavaScript supports references or pointers. References allow you to point a variable at another variable, and then access the original contents of the variable pointed too through the reference. So instead of creating a new copy of data in a variable, the reference is pointing to the variable memory location and allowing you to access it directly. This concept is important since we will use this in the technique I am about to describe.
var myArray = new Array("Some Text");
var refArray = myArray;
refArray[0] = "test";
alert(myArray[0]);
In the above code block I showed how to create a reference, refArray, to the array, myArray. I also included some code which will output "test" to demonstrate the concept. The reason it will output "test" instead of "Some Text" is because we overwrite the first entry in the reference refArray, which as noted before references the array myArray. Since the reference is not a new copy but instead a pointer to the original data we are actually modifying the contents of myArray from refArray.
Making It MultidimensionalSo taking the two above concepts we can create something very similar to a multidimensional array by assigning to each entry in an array a reference to another array. Let me show you a code example to make this technique really clear to you.
var x = new Array (1, 2, 3, 4);
var multiArray = new Array();
multiArray[0] = x;
var anotherMulti = new Array( new Array( 1, 2, 3, 4) );
In the above code we created a standard array x with entries for 1-4. In the next line we created a new array multiArray and in the following line reference the x array in the first entry. If we where to output multiArray[0][0] we would get 1. I also included an example of how to do it all in one line.
Other ImprovedSource Articles:
JavaScript bracket notation allows you to use strange variable names
How to detect if your in a frame via JavaScript
How to do custom sorting in Javascript on arrays