7.06.2013

How to declare a Two-Dimensional Array in the JavaScript

Because of my work mission, I need review the programming language - JavaScript nearly.

This topic will introduce that how to declare a Two-Dimensional Array in the JavaScript.

If we only need One-Dimensional Array, we could do this as you know:
var temp = new Array(5);
It is an array that have five elements. Or:
var temp = new Array("JavaScript", "jQuery", "Perl", "Ruby", "HTML5");
We also could declare their contents directly.

But, if we need a Two-Dimensional Array that 4 multiplied by 2, how can we to do??
var aryTemp = function() {

    var virTemp = new Array(4);
    var x = 0, y = 0;
    for (x = 0; x < 4; x++) {
        virTemp[x] = new Array(2);
        for (y = 0; y < 2; y++)
            virTemp[x][y] = "Hello!! JavaScript!! \n";
    }
    return virTemp;
};
The Two-Dimensional Array was named "aryTemp", we used an anonymous function to initialize it.

We declare "virTemp" to an array in the anonymous function.

In the virTemp[], we must initialize an array for each elements.

Otherwise, we could create a function to read this Two-Dimensional Array:
function Init() {

    var j = 0, k = 0;
    for (j = 0; j < 4; j++) {
        for (k = 0; k < 2; k++)
            window.document.write("aryTemp()[" + j + "][" + k + "]: " + aryTemp()[j][k] + "\n");
        window.document.write("\n");
    }
    return;
}
To pay attention to a key word: aryTemp(). Because of we used an anonymous function to initialize aryTemp, we must add "()" when we use aryTemp.

The total solution as below:
<!DOCUMENT html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.prg/TR/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" language="JavaScript">
var aryTemp = function() {

    var virTemp = new Array(4);
    var x = 0, y = 0;
    for (x = 0; x < 4; x++) {
        virTemp[x] = new Array(2);
        for (y = 0; y < 2; y++)
            virTemp[x][y] = "Hello!! JavaScript!! \n";
    }
    return virTemp;
};

function Init() {

    var j = 0, k = 0;
    for (j = 0; j < 4; j++) {
        for (k = 0; k < 2; k++)
            window.document.write("aryTemp()[" + j + "][" + k + "]: " + aryTemp()[j][k] + "\n");
        window.document.write("\n");
    }
    return;
}
</script>
</head>
<body OnLoad="Init(); ">
</body>
</html>

沒有留言:

張貼留言