Log in

View Full Version : Multi-Dimensional Array



locbtran
01-18-2013, 01:10 AM
I have an array, called, "myArray". Inside this myArray are 4 more arrays, "m0, m1, m2, m3".
How do I access all the elements in all the array?

Here's my code, :

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<body>
<script>
var m0 = [0, 1, 2, 3, 4];
var m1 = [5, 6, 7, 8, 9];
var m2 = [10, 11, 12, 13, 14];
var m3 = [15, 16, 17, 18, 19];

var myArray = [m0, m1, m2, m3];


for (var i = 0; i < myArray.length; i++) {
for (var j = 0; j < ("m"+i).length; j++) {
document.writeln(myArray[i][j]);
}
}
</script>
</body>
</html>


This code only give me the first 2 elements in each array.
But, I would like to get all the elements in all the arrays.

tks

jscheuer1
01-18-2013, 03:26 AM
In this line:



for (var j = 0; j < ("m"+i).length; j++) {

the red part is a string which will resolve to - m0, m1, m2 and then m3. As strings they are each only 2 characters in length, so that's what you're getting. Here they're converted to what they are, properties of the window object, where their native length as arrays can be read:


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<body>
<script>
var m0 = [0, 1, 2, 3, 4];
var m1 = [5, 6, 7, 8, 9];
var m2 = [10, 11, 12, 13, 14];
var m3 = [15, 16, 17, 18, 19];

var myArray = [m0, m1, m2, m3];


for (var i = 0; i < myArray.length; i++) {
for (var j = 0; j < window["m"+i].length; j++) {
document.writeln(myArray[i][j]);
}
}
</script>
</body>
</html>

The window (assuming this is a web page) is the default object in javascript. But you needn't address them that way, this will also work:


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>

<body>
<script>
var m0 = [0, 1, 2, 3, 4];
var m1 = [5, 6, 7, 8, 9];
var m2 = [10, 11, 12, 13, 14];
var m3 = [15, 16, 17, 18, 19];

var myArray = [m0, m1, m2, m3];


for (var i = 0; i < myArray.length; i++) {
for (var j = 0; j < myArray[i].length; j++) {
document.writeln(myArray[i][j]);
}
}
</script>
</body>
</html>

The for loop is less efficient than the while loop, so I would (also changing other things around a little) do it more like:


var myArray = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]
], i = -1, j;

while (++i < myArray.length){
j = -1;
while(++j < myArray[i].length){
document.writeln(myArray[i][j]);
}
}

There are surely numerous other ways to approach it.