Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Feb 9, 1998

JavaScript Multi-Dimensional Arrays?

Multi-dimensional arrays can be represented by arrays of arrays. For example, suppose that you want to create a 3x3 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 < Brady.length; ++ i)
	Brady [i] = new Array(3);
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 ("<table border>") ;
	var row; for (row = 0; row < ; 			
	array.length; ++row)
	{ 
		document.writeln (" <tr>");
			var col for (col = 0; col < array
	 		[row].length; ++col) 
			document.writeln (" <td>" + array
				[row] [col] + "</td>"); 
			document.writeln (" </tr>"); 
	} 
	document.writeln ("</table>");
}

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)!
Charlton Rose
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap