home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

JavaScript: The Definitive Guide

Previous Chapter 8

8.4 Creating Arrays

Since arrays are the same thing as objects, they can be created in exactly the same way as objects are with the new operator:

a = new Object();
a[0] = 1; 
a[1] = 2;
  ... etc ...

Just as you write custom constructor methods to perform initialization on newly created objects, you can also write your own custom array constructor functions as shortcuts for array initialization. Example 8.1 shows a constructor that creates an array, initializes a size property of the array, and then initializes size elements (starting at 1, rather than 0) to a value of 0. This is useful when you want to know exactly how many elements your array contains, and want to be sure that all elements have a defined value.

Example 8.1: An Array Constructor

// The constructor function
function EmptyArray(length)
    this.size = length;
    for(var i = 1; i <= length; i++)
        this[i] = 0;   
// Using the constructor
a = new EmptyArray(32);

In Navigator 3.0 and Internet Explorer 3.0, there is a predefined Array() constructor function that you can use to create arrays. You can use this constructor in three distinct ways. The first is to call it with no arguments:

a = new Array();
This method creates an empty array with no elements. It is like calling new Object(), except that it gives the newly created object (i.e., an array) a length property set to 0.

The second technique is to call the Array() constructor with a single argument, which specifies a length:

a = new Array(10);
This technique creates an empty array as well, but it sets the length property of the array to the value specified.

The final technique allows you to specify values for the first n elements of an array:

a = new Array(5, 4, 3, 2, 1, "testing, testing");
In this form, the constructor is passed two or more arguments. Each argument specifies an element value and may be of any type. Elements are assigned to the array starting with element 0. The length property of the array is set to the number of arguments that were passed to the constructor.

Remember that the Array() constructor is available only in Navigator 3.0 and later. In 2.0, you must write your own array constructor functions. And, of course, in either 2.0 or 3.0, you can use any object, no matter how you create it, as an array. Bear in mind, though, that there are some significant differences (which we'll explore later) between arrays in Navigator 2.0 and Navigator 3.0, and you must carefully take these into account when backward compatibility with Navigator 2.0 is required.

Previous Home Next
Array/Object Dual Nature Book Index Array Length Property

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell