Creating Arrays

We can create a new array with a data literal (i.e., simply typing out all the elements) or with the special built-in array constructor function, Array( ).

The Array Constructor

To create an array with the Array( ) constructor, we use the new operator followed by the Array keyword followed by parentheses, which yields an empty array (one with no elements). We normally assign a newly created array to a variable or other data container for future reference. For example:

var myList = new Array( );  // Store an empty array in variable myList

We often want to assign initial values to an array’s elements. We can do so by passing parameters to the Array( ) constructor when invoking it. Depending on the parameters we supply, the constructor invocation has different effects.

When we supply more than one argument to the Array( ) constructor or when we supply a single nonnumeric argument to the Array( ) constructor, each argument becomes one of the element values in our new array. For example:

var frameLabels = new Array("intro", "section1", "section2", "home");

The array stored in frameLabels would have the following elements:

0: "intro"
 1: "section1"
 2: "section2"
 3: "home"

When we supply exactly one numeric argument to the Array( ) constructor, it creates an array with the specified number of empty placeholder elements:

var myList = new Array(14); // Creates an array with 14 empty elements

Arguments passed to the Array( ) constructor can be any legal expression, including compound ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.