bbb Home
Arrays Contents        

ARRAY FUNDAMENTALS

1D array

Index Item
0 Jo
1 Bob
2 Skippy
... ...
N Bif

USING ARRAYS

var sNames = new Array()   //creates with 0 elements

var iNumbers = new Array(4)  //array with 4 elements (0 to 3)

var fVars = new Array(3.14158, 6.02, 2.54)  //3 elements

sNames[0] = "Jo"

iNumbers[3] = 4

fVars[1] = 6.023

alert(iNumbers[3])

var sQ = sNames[0]

alert(sNames[iNumbers[3])

ARRAY METHODS AND PROPERTIES

var myArray = new Array(3,11,4,2)

myArray.sort()   //Arranges elements as 11,2,3,4

var myArray = new Array("c", "a", "b")

alert(myArray.length)  //will display 3

2D ARRAYS

var sRow0 = new Array()
var sRow1 = new Array()
var sRow2 = new Array()
var sTable = new Array(sRow0, sRow1, sRow2)
sTable[0][0] = "Row0Col0"
alert(sTable[0][0])

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


EXAMPLE

Font: 8pt   12pt   20pt   24pt   Width: Min. 50%   75%   100%   

PRACTICE

1. Write statements to accomplish the following:
  1. Declare an array called iA to hold 5 numbers.
  2. Declare an array called iB to hold the numbers 1, 3, and 4.
  3. Declare an array called sC to hold the strings "1", "2", and "4".
  4. Declare an array called fD. You don't know how many items will be in the array.
  5. Assign 5 to the very first element in array iB in b above.
  6. Assign 10 to the very last element in array iB in b above.
  7. Assign "a" and "b" to the array fD in d.
  8. Display the 2nd element of array sC in an alert.
  9. Display the length of array sC in an alert.
  10. Sort array sC.

2. Create a page that allows the user to add items to an array, display all of the items, display the length of the array, and sort the array.

3. Create a 10-by-10 2D array to hold the contents of the multiplication table. For example, cell(2,3) should hold the value 6. Assign the elements using for loops and then write out the table to the page.

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

5.  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


SELF-QUIZ