O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Determining the Size of an Array

All arrays come with an instance variable named length, which indicates the current number of elements in the array (including undefined elements). To access an array's length variable, we use the dot operator, like so:

theArray.length

Here are a few examples:

var list:Array = [34, 45, 57];
trace(list.length);               // Displays: 3

var words:Array = ["this", "that", "the other"];
trace(words.length);              // Displays: 3

var cards:Array = new Array(24);  // Note the single numeric argument
                                  // used with the Array() constructor
trace(cards.length);              // Displays: 24

The length of an array is always 1 greater than the index of its last element. For example, an array with elements at indexes 0, 1, and 2 has a length of 3. And an array with elements at indexes 0, 1, 2, and 50 has a length of 51. 51? Yes, 51. Even though indexes 3 through 49 are empty, they still contribute to the length of the array. The index of the last element of an array is always theArray.length − 1 (because index numbers begin at 0, not 1). Therefore, to access the last element of theArray, we use the following code:

theArray[theArray.length − 1]

If we add and remove elements, the array's length variable is updated to reflect our changes. In fact, we can even set the length variable to add or remove elements at the end of an array. This is in contrast to the String class's length variable, which is read-only. Shortening the length of an array removes elements beyond the new length.

Using an array's ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required