8.4 Creating ArraysSince 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(); The second technique is to call the Array() constructor with a single argument, which specifies a length:
a = new Array(10); 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"); 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. |
|