About referencing and finding length

When you work with arrays, you often need to know how many items exist in the array. This can be very useful when writing for loops that iterate through every element in the array and execute a series of statements. You can see an example in the following snippet:

var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
trace(monthArr); // Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
trace(monthArr.length); // 12
var i:Number;
for (i = 0; i < monthArr.length; i++) {
    monthArr[i] = monthArr[i].toUpperCase();
}
trace(monthArr); // JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC

In the previous example, you create an array and populate it with month names. The contents are displayed, and also the array's length. A for loop iterates over each item in the array and converts the value to uppercase, and the array contents are displayed again.

In the following ActionScript, if you create an element at array index 5 in an array, the length of the array returns 6 (because the array is zero based), and not the actual number of items in the array as you might expect:

var myArr:Array = new Array();
myArr[5] = "five";
trace(myArr.length); // 6
trace(myArr); // undefined,undefined,undefined,undefined,undefined,five

For more information on for loops, see Using for loops. For information on the array access operator, see Using dot and array access operators.

For a sample source file, array.fla, that illustrates array manipulation using ActionScript, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/Arrays folder to access the sample. The code in the sample creates an array and sorts, adds, and removes items of two List components.