8.3  2-Dimensional Arrays 

Index Code Tester

OBJECTIVE

DISCUSSION

2D Array 

0 1 2 ... N
0 a b c ... d
1 e f g ... h
2 i j k ... l
... ... ... ... ... ...
M m n o ... p

Creating and Using Arrays

 
var sRow0 = new Array()
var sRow1 = new Array()
var sRow2 = new Array()
var sTable = new Array(sRow0, sRow1, sRow2)
 
 
sTable[0][0] = "Row0Col0"
sTable[0][1] = "Row0Col1"
sTable[2][2] = "Row2Col2"
sTable[2][5] = "Row2Col5"
 
alert(sTable[2][5])
alert(sTable.length)
alert(sTable[0].length)
alert(sTable[1].length)
alert(sTable[2].length)

 

EXERCISES

#1 to #4 are all related. 

1.  Create a 10-by-10 array that holds the multiplication table.  For example, cell (2,3) should hold the value 6. 

2. Create a function to set the values of the array in #1.  You will need to use a for loop in a for loop.

3. Create a function to display the array in #1. 

4.  Create a program to demonstrate #1 to #3.

5.  Create a general function that accepts any 2D array and returns a string with the contents of the array in tabular form.

6.  Write code that initializes a 10 by 10 array of characters so that all elements are "X" except those on the diagonal which are set to "O".  If the array is displayed it would look like:

OXXXXXXXXX
XOXXXXXXXX
XXOXXXXXXX
XXXOXXXXXX
XXXXOXXXXX
XXXXXOXXXX
XXXXXXOXXX
XXXXXXXOXX
XXXXXXXXOX
XXXXXXXXXO

 

LINKS AND HELP

http://javascript.about.com/library/weekly/aa111201a.htm