Determining the Size of an Array

All arrays come with a built-in property named length, which indicates the current number of elements (including empty elements). To access an array’s length property, we use the dot operator, like so:

               arrayName.length

An array’s length property tells us how many elements are in the array. Here are a few examples:

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

myWords = ["this", "that", "the other"];
trace(myWords.length);  // Displays: 3, the number of elements, 
                        // not the number of words or characters

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

The length of an array is always one 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 last element of an array is always myArray [ myArray .length - 1], because index numbers begin at 0, not 1.

If we add and remove elements, the array’s length property is updated to reflect our changes. In fact, we can even set the length property to add or remove elements at the end of an array.

What is an array’s length property good for, you ask? Using an array’s length property, we can create a loop that accesses all the elements of an array as we saw in ...

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.