Previous Topic Tutorial Table of Contents Next Topic
 
 

The Array Object

 
Arrays are data structures that store information in a set of adjacent memory addresses.  In practice, this means is that you can store other variables and objects inside an array and can retrieve them from the array by referring to their position number in the array.  Each variable or object in an array is called an element. 

Unlike stricter languages, such as Java, you can store a mixture of data types in a single array.  For example, you could have array with the following four elements:  an integer, a window object, a string and a button object. 

In addition, JavaScript arrays are always expandable -- meaning that the number of elements in a JavaScript array is not constrained after the array is first declared or initialized. 

Why should you learn about arrays?  Here are three good reasons:  

  1. They can greatly simplify your programming [how?];
  2. The DOM stores objects as arrays and you can reference them as elements in an array [how?];
  3. You can store small tables of information in them [how?].
The details of each of these points will be explained below. 

To reference an element in an array, one appends square brackets to the end of the array name.  For example, let us name the array mentioned above "arrayList".  It's structure would look like this:  

arrayList[0] = 7           // an integer 
arrayList[1] = newWind     //a window object ref 
arrayList[2] = "blue suede shoes"   // a string   
arrayList[3] = input       // a button reference     

(where input = newWind.document.formName.buttonName) 

The notation arrayList[1] is read "arrayList sub 1".

The position number of an element in an array is called the index number. Note that the first element in an array has index number 0, not 1.  This is called zero-based indexing and can be confusing to novice programmers.  The index number of an element is one less than it's position.  For example, the third element of arrayList has index number 2.  Thus, the string "blue suede shoes" is the third element in arrayList.  Forgetting this can lead to what are called "off-by-one errors". 
 

Creating an Array 

In JavaScript, arrays are objects and they can be constructed in one of three ways. 

1.  JavaScript allows you to instantiate an array using the "new" operator, as follows: 

arrayList = new Array(4) 

This creates a new array called "arrayList" with 4 empty elements.  Note that by declaring an array this way, you are not limited to only 4 elements--you can always expand the array.  Specifying the number of elements is optional, so you could also write: 

arrayList = new Array() 
 
To define the elements of the array, you would then specify the elements.  For example to make an array of book titles (which would be string objects in JavaScript), you might write: 

books = new Array(5) 
books[0] = "Jane Eyre" 
books[1] = "The Stranger" 
books[2] = "Oliver Twist" 
books[3] = "Rebecca" 
books[4] = "Stranger in a Strange Land" 

You could also add: 
books[82] = "The Mote in God's Eye" 

This is allowable in JavaScript.  By doing this, you would have expanded the array to have 83 elements and elements 5 through 81 would be empty (null) elements. 

This method is compatible with all versions of JavaScript. 

2.  The second way is to supply the elements as parameters to the array constructor: 

books = new Array("Jane Eyre","The Plague","Oliver Twist","Rebecca","Stranger in a Strange Land") 

Note that there are no spaces between the parameters. 

For long arrays, I do not recommend using this method due to the inability to write single line statements over many lines. (In JavaScript, unlike most other programming languages, a carriage return (newline) is considered the end of the programming statement. Most other (C-based) languages mark the end of programming statement with a semi-colon.)

3.  In JavaScript 1.2 environments, you can also create an array using brackets to specify the elements to be put in the array: 

arrayList = [ 2, 4, 15, 'a', "once upon a time" ] 

This statement creates an array called arrayList with 5 elements.  No "new" constructor statement is required.   

The first three elements are integers, the fourth is a character and the final element is a string.  Thus, the value of arrayList[3] is the character 'a'. 

The Virtues of Using Arrays 

Arrays simplify your programs 

Suppose you wrote a web page asking users what their favorite book was.  In response to their answer, you would like to respond with:  "That is one of my favorite books too!" or "That one is not on my list of favorites." 

Here is one way you could check the user's input against your list of favorite books: 

var input = document.formName.textFieldName 
var fav1 = "Jane Eyre"  
var fav2 = "The Stranger"  
var fav3 = "Oliver Twist"  
var fav4 = "Rebecca"  
var fav5 = "Stranger in a Strange Land" 

if ( fav1 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else if ( fav2 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else if ( fav3 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else if ( fav4 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else if ( fav5 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else { 
    document.write("That one is not on my list of favorites."); 
} 

This method is very space wasteful and repetitive.  Imagine how long and ugly it would be if you had 15 favorite books.  Or 30. 

An alternative way to write this script would be: 

if ( fav1 == input || fav2 == input || fav3 == input || fav4 == input || fav5 == input ) { 
    document.write("That is one of my favorite books too!"); 

}  else { 
    document.write("That one is not on my list of favorites."); 
} 

By using the Boolean OR operator, ||, this method saves a considerable amount of space over the last one.  However, it still becomes bulky quite quickly as the number of variables you want to test increases.  In addition, this method runs into the problem of not being able to write single code phrases over multiple lines in JavaScript.  (Meaning that long lines must be written on a single line--making them hard to see and a possible cause of error in some Unix text editors.) 

The right way to write this script is with arrays.  First you would define an array with the list of your favorite books: 

books = new Array(5) 
books[0] = "Jane Eyre" 
books[1] = "The Stranger" 
books[2] = "Oliver Twist" 
books[3] = "Rebecca" 
books[4] = "Stranger in a Strange Land" 

Then you use a for loop to iterate over each element of the array and compare it to the user's input.  The length property of the Array object returns the number of elements in the array and can be used to create the conditional statement in a for loop: 

for (var i = 0; i < books.length; i++) { 
    if (books[i] == input) { 
        document.write("That is one of my favorite books too!"); 
        break; 
    } 
} //end for loop 

if (i == books.length) { 
    document.write("That one is not on my list of favorites.") 
}

The for loop iterates over each element of the array "books".  As it does so, it checks each element to see if it matches the user's input.  If it matches, it tells the user with a document.write() command and then uses a break command to jump out of the for loop. 

break is an inbuilt JavaScript command that causes the program to jump out of a repetition loop--that is, a for loop or a while loop.  Without the break statement, the for loop would cycle through all five books, even if the an earlier book had matched the user's input.  Put another way, without the break statement, the variable i would be equal to 5 when the for loop was finished executing.  In that case, the if statement after the for loop would evaluate to true. 

With the break statment, if the user input matches, say, books[1], then when the for loop was finished executing i would be equal to 1.  A break statement causes the flow of program execution to immediately leave the repetition loop that contains it.  The first statement after the closing bracket of the for loop is the next thing to be executed.  In this case, the if statement following the for loop would be tested and it would evaluate to false. 
 

The DOM stores objects as arrays and you can reference them as elements in an array

Many objects in the DOM have elements that can occur multiple times.  For example, a window can have multiple frames.  A document can have multiple forms or multiple images.  A form can have multiple "widgets", which in the DOM are called "elements".  To help keep track of them all, the DOM automatically constructs an array with a reference to each element for each object that can have multiple elements.  This array is stored as a property of the parent element and it can be referenced like any other property:  with dot syntax.

Suppose you load into your browser a document that has 3 images.  "images[i]" is a property of the document object.  Thus the first image (first here means first to occur in the html source code) can be referenced as:

document.images[0]

Here are a few of the arrays elements in the DOM and their parent containers:

Window object
frames[i]

Document object
applets[i]
forms[i]
images[i]
layers[i]
links[i]

Form object
elements[i]

You can store tables of information in arrays 

A single array can be thought of as a single row of values in a table.  How then can we add more rows to our "table"?  We could just define a set of arrays, like this: 

var row1 = new Array() 
var row2 = new Array() 
var row3 = new Array() 
var row4 = new Array() 
var row5 = new Array() 

and then specify the elements of each array.  

Another way to do it is to create an array of arrays or create an array of user-defined objects  

An array of arrays might look this: 

var book = new Array() 
book[0] = new Array() 
book[1] = new Array() 
book[2] = new Array() 
book[3] = new Array() 
book[4] = new Array() 

Thus, each element of the array book is itself another array--in other words, we've created an array of arrays. 

Suppose we wanted to keep a table of information about our five favorite books: 
 
 
 
Name
Author
Date of Publication
Book 1 Jane Eyre C. Bronte
1847
Book 2 The Stranger A. Camus
1942
Book 3 Oliver Twist C. Dickens
1846
Book 4 Rebecca D. DuMaurier
1938
Book 5 Stranger in a Strange Land R. Heinlein
1961

Using an array of arrays, we would input the data this way: 

book[0][0] = "Jane Eyre" 
book[0][1] = "C. Bronte" 
book[0][2] = "1847" 
book[1][0] = "The Stranger" 
book[1][1] = "A. Camus" 
book[1][2] = "1942" 
book[2][0] = "Oliver Twist" 
book[2][1] = "C. Dickens" 
book[2][2] = "1846" 
book[3][0] = "Rebecca" 
book[3][1] = "D. DuMaurier" 
book[3][2] = "1938" 
book[4][0] = "Stranger in a Strange Land" 
book[4][1] = "R. Heinlein" 
book[4][2] = "1961" 

While this may look confusing at first, it becomes easier to understand when you remember this mantra:  "row first, column second".  Thus, the string "C. Dickens" is in row 2, column 1 (remember that arrays are zero-indexed, so that the first row and first column are labelled 0, not 1.) 

Creating an Array of Objects 

An alternative way to bring in a small table of data to your web pages is to create an array of objects.  In JavaScript, you can define your own objects, complete with their own properties.  To create a new object, you must write a constructor method and then use the new operator to create objects from it. 

Here is an example constructor method: 

function bookInfo( name, author, pubDate ) { 
  
    this.name = name; 
    this.author = author; 
    this.date = pubDate; 
} 

This function creates an object called bookInfo.  bookInfo receives three arguments and assigns those to its three properties:  name, author and date.  You can now reference the properties of this user-defined object the same way you reference properties of objects in the DOM--using dot syntax:  bookInfo.name 

As the constructor method can be used to create as many different bookInfo objects as we want, let us now create an array of objects using the constructor method we just defined: 

var book = new Array(); 
book[0] = new bookInfo("Jane Eyre", "C. Bronte", "1847"); 
book[1] = new bookInfo("The Stranger", "A. Camus", "1942"); 
book[2] = new bookInfo("Oliver Twist", "C. Dickens", "1846"); 
book[3] = new bookInfo("Rebecca", "D. DuMaurier", "1938"); 
book[4] = new bookInfo("Stranger in a Strange Land", "R. Heinlein", "1961"); 

What did this do?  It created five new "bookInfo" objects from the bookInfo constructor object and put each of those objects in the array "book".  The new keyword automatically creates a new object by calling the constructor method specified after it (in this case the method "bookInfo()").  A constructor method automatically returns a reference to the object (this is predefined in the JavaScript language).  This reference is what gets stored in the array elements, book[0], book[1], etc. 

In other words, book[0] is two things:  1) an element of the array "book" and 2) a reference to a bookInfo object (that has three defined properties).  Ditto for book[1], book[2], book[3], book[4], except that they all refer to different bookInfo objects. 

Take a look at this script to see this array of objects in action.


Previous Topic Tutorial Table of Contents Next Topic