devxlogo

JavaScript Multi-Dimensional Arrays?

JavaScript Multi-Dimensional Arrays?

Multi-dimensional arrays can be represented by arrays of arrays. For example, suppose that you want to create a 3×3 matrix, called Brady, and fill it with the strings shown in the following table:

 		col 0	col 1	col 2   row 0	"Marsha"	"Carol"	"Greg"   row 1	"Jan"	"Alice"	"Peter"   row 2	"Cindy"	"Mike"	"Bobby"

To create the array, you should first allocate storage for each element:

 Brady = new Array(3) for (i = 0; i 

Although Brady is just a one-dimensional array, the fact that each of Brady's elements is initialized with yet another one-dimensional array means that Brady is an array of arrays--in other words, a two-dimensional array. Each element in the Brady array is a row in the matrix, and each row is an array of three elements.

Obviously, the expression Brady represents an array. In this case, however, so do the expressions Brady [0], Brady [1], and Brady [2]! This means that we can populate the Brady array with the following code:

 Brady [0] [0] = "Marsha";Brady [0] [1] = "Carol";Brady [0] [2] = "Greg";Brady [1] [0] = "Jan";Brady [1] [1] = "Alice";Brady [1] [2] = "Peter";Brady [2] [0] = "Cindy";Brady [2] [1] = "Mike";Brady [2] [2] = "Bobby";

Arrays would not be useful if their members could not be indexed with variables and expressions. The following JavaScript code will display arbitrary two-dimensional arrays of strings (such as the Brady array) in HTML tables. Please carefully observe the manner in which the row and col indices are used to iterate through each element of array. (If you are rusty on HTML table syntax, you might want to review it before wading through this function).

 function print_2d_string_array(array) { 	document.writeln ("") ;	var row; for (row = 0; row ");			var col for (col = 0; col " + array				[row] [col] + ""); 			document.writeln (" "); 	} 	document.writeln ("
");}print_2d_string_array (Brady);

If you really want a challenge, try making three-dimensional arrays using this same technique(an array of arrays of arrays)!

devx-admin

Share the Post: