Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Multidimensional Arrays - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Arrays

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Multidimensional Arrays - JavaScript(JS)

Multidimensional arrays with two subscripts are often used to represent tables of values consisting of information arranged in rows and columns.

Multidimensional Arrays

 

Multidimensional arrays with two subscripts are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table el-ement, we must specify the two subscripts; by convention, the first identifies the element’s row, and the second identifies the element’s column. Arrays that require two subscripts to identify a particular element are called two-dimensional arrays.

 

Multidimensional arrays can have more than two dimensions. JavaScript does not support multidimensional arrays directly, but does allow the programmer to specify arrays whose elements are also arrays, thus achieving the same effect. When an array contains one-dimensional arrays as its elements, we can imagine these one-dimensional arrays as rows of a table, and the positions in these arrays as columns. Figure 10.12 illustrates a two-dimensional array named a that contains three rows and four columns (i.e., a three-by-four array—three one-dimensional arrays, each with 4 elements). In general, an array with m rows and n columns is called an m-by-n array.

 

Every element in array a is identified in Fig. 10.12 by an element name of the form a[ i ][ j ]; a is the name of the array, and i and j are the subscripts that uniquely identify


the row and column, respectively, of each element in a. Note that the names of the ele-ments in the first row all have a first subscript of 0; the names of the elements in the fourth column all have a second subscript of 3.

 

Arrays of One-Dimensional Arrays

 

Multidimensional arrays can be initialized in declarations like a one-dimensional array. Array b with two rows and two columns could be declared and initialized with the state-ment

 

var b = [ [ 1, 2 ], [ 3, 4 ] ];

 

The values are grouped by row in square brackets. The array [1, 2] initializes element b[0], and the array [3, 4] initializes element b[1]. So 1 and 2 initialize b[0][0] and b[0][1], respectively. Similarly, 3 and 4 initialize b[1][0] and b[1][1], respectively. The interpreter determines the number of rows by counting the number of sub initializer lists—arrays nested within the outermost array. The interpreter determines the number of columns in each row by counting the number of values in the sub-array that initializes the row.

 

Two-Dimensional Arrays with Rows of Different Lengths

The rows of a two-dimensional array can vary in length. The declaration

 

var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

 

creates array b with row 0 containing two elements (1 and 2) and row 1 containing three elements (3, 4 and 5).

 

Creating Two-Dimensional Arrays with new

A multidimensional array in which each row has a different number of columns can be allocated dynamically, as follows:

var b;                            

b = new Array( 2 );                 // allocate rows

b[      0       ] = new Array( 5  );       // allocate   columns for row 0

b[      1       ] = new Array( 3  );       // allocate   columns for row 1

The preceding code creates a two-dimensional array with two rows. Row 0 has five col-umns, and row 1 has three columns.

 

Two-Dimensional Array Example: Displaying Element Values

Figure 10.13 initializes two-dimensional arrays in declarations and uses nested forin loops to traverse the arrays (i.e., manipulate every element of the array).

 

        <?xml version = "1.0" encoding = "utf-8"?>

 

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

        <!-- Fig. 10.13: InitArray3.html -->

 

        <!-- Initializing multidimensional arrays. -->

 

<html xmlns = "http://www.w3.org/1999/xhtml">

      <head>

 

      <title>Initializing Multidimensional Arrays</title>

 

        <script type = "text/javascript">

        <!--

 

var array1 = [ [ 1, 2, 3 ], // first row

[         4, 5, 6         ] ]; // second row

var array2 = [ [    1, 2 ], // first row

[         3 ], // second row

[         4, 5, 6         ] ]; // third row

                  

        outputArray( "Values in array1 by row", array1 );

 

        outputArray( "Values in array2 by row", array2 );

 

        function outputArray( heading, theArray )

{

document.writeln( "<h2>" + heading + "</h2><pre>" );

                                     

// iterates through the set of one-dimensional arrays

          for ( var i in theArray )          

{                           

                   // iterates through the elements of each one-dimensional

                   // array

                   for ( var j in theArray[ i ] )     

                   document.write( theArray[ i ][ j ] + " " );  

                                     

                   document.writeln( "<br />" );

} // end for

        document.writeln( "</pre>" );

 

        } // end function outputArray

        // -->

 

        </script>

 

        </head><body></body>

 

</html>


Fig. 10.13 | Initializing multidimensional arrays.

The program declares two arrays in main script (in the XHTML head element). The declaration of array1 (lines 12–13 provides six initializers in two sublists. The first sublist initializes the first row of the array to the values 1, 2 and 3; the second sublist initializes the second row of the array to the values 4, 5 and 6. The declaration of array2 (lines 14– 16) provides six initializers in three sublists. The sublist for the first row explicitly initial-izes the first row to have two elements, with values 1 and 2, respectively. The sublist for the second row initializes the second row to have one element, with value 3. The sublist for the third row initializes the third row to the values 4, 5 and 6.

 

The script calls function outputArray from lines 18–19 to display each array’s ele-ments in the web page. Function outputArray (lines 21–37) receives two arguments—a string heading to output before the array and the array to output (called theArray). Note the use of a nested forin statement to output the rows of each two-dimensional array. The outer forin statement iterates over the rows of the array. The inner forin state-ment iterates over the columns of the current row being processed. The nested forin statement in this example could have been written with for statements, as follows:

 

for ( var i = 0; i < theArray.length; ++i ) {

 

for ( var j = 0; j < theArray[ i ].length; ++j ) document.write( theArray[ i ][ j ] + " " );

 

document.writeln( "<br />" );

 

}

 

In the outer for statement, the expression theArray.length determines the number of rows in the array. In the inner for statement, the expression theArray[i].length deter-mines the number of columns in each row of the array. This condition enables the loop to determine, for each row, the exact number of columns.

 

Common Multidimensional-Array Manipulations with for and forin Statements

 

Many common array manipulations use for or forin repetition statements. For exam-ple, the following for statement sets all the elements in the third row of array a in Fig. 10.12 to zero:

 

for ( var col = 0; col < a[ 2 ].length; ++col ) a[ 2 ][ col ] = 0;

 

We specified the third row; therefore, we know that the first subscript is always 2 (0 is the first row and 1 is the second row). The for loop varies only the second subscript (i.e., the column subscript). The preceding for statement is equivalent to the assignment state-ments

 

a[ 2 ][ 0 ] = 0;

a[ 2 ][ 1 ] = 0;

a[ 2 ][ 2 ] = 0;

a[ 2 ][ 3 ] = 0;

 

The following forin statement is also equivalent to the preceding for statement:

 

for ( var col in a[ 2 ] )

a[ 2 ][ col ] = 0;

 

The following nested for statement determines the total of all the elements in array a:

 

var total = 0;

 

for ( var row = 0; row < a.length; ++row )

 

for ( var col = 0; col < a[ row ].length; ++col ) total += a[ row ][ col ];

 

The for statement totals the elements of the array, one row at a time. The outer for state-ment begins by setting the row subscript to 0, so that the elements of the first row may be totaled by the inner for statement. The outer for statement then increments row to 1, so that the elements of the second row can be totaled. Then the outer for statement incre-ments row to 2, so that the elements of the third row can be totaled. The result can be dis-played when the nested for statement terminates. The preceding for statement is equivalent to the following forin statement:

 

var total = 0;

 

for ( var row in a )

 

for ( var col in a[ row ] ) total += a[ row ][ col ];

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.