JavaScript Object Literal as Multidimensional Array
Let’s say I defined 2 arrays in JavaScript:
var a1 = new Array(1,2);
var a2 = new Array(3,4);
and a variable :
var a3 = ‘yes’;
I want to combine these 2 arrays and the variable into a multidimensional array. If you use a standard notation for JavaScript multi-dimensional arrays, you can only refer to array elements by index:
Build a multidimensional array that includes the previously defined arrays a1, a2 and the variable a3:
var arr = [a1, a2, a3];
Get the value of the first element in the a1 array:
alert (arr[0][0]);
You can’t use arr.a1[0]. It will be undefined.
If you want to refer to array elements by name, you need to have an object literal act as a multidimensional array:
Build an object literal:
var obj = {
a : a1,
b : a2,
c: a3
}
Now you can refer to individual elements as follows:
obj.a[0]
or
obj.c
