User Guide
Indexed arrays 231
trace(oceans[2]); // output: undefined
trace(oceans.length); // output: 5
You can truncate an array using an array’s length property. If you set the length property of
an array to a length that is less than the current length of the array, the array is truncated,
removing any elements stored at index numbers higher than the new value of
length minus
1. For example, if the
oceans array were sorted such that all valid entries were at the
beginning of the array, you could use the
length property to remove the entries at the end of
the array, as shown in the following code:
var oceans:Array = ["Arctic", "Pacific", "Victoria", "Aral", "Superior"];
oceans.length = 2;
trace(oceans); // output: Arctic,Pacific
Sorting an array
There are three methods—reverse(), sort(), and sortOn()—that allow you to change the
order of an array, either by sorting or reversing the order. All of these methods modify the
existing array. The
reverse() method changes the order of the array such that the last
element becomes the first element, the penultimate element becomes the second element, and
so on. The
sort() method allows you to sort an array in a variety of predefined ways, and
even allows you to create custom sorting algorithms. The
sortOn() method allows you to sort
an indexed array of objects that have one or more common properties that can be used as sort
keys.
The
reverse() method takes no parameters and does not return a value, but allows you to
toggle the order of your array from its current state to the reverse order. The following
example reverses the order of the oceans listed in the
oceans array:
var oceans:Array = ["Arctic", "Atlantic", "Indian", "Pacific"];
oceans.reverse();
trace(oceans); // output: Pacific,Indian,Atlantic,Arctic
The sort() method rearranges the elements in an array using the default sort order. The
default sort order has the following characteristics:
■ The sort is case-sensitive, which means that uppercase characters precede lowercase
characters. For example, the letter D precedes the letter b.
■ The sort is ascending, which means that lower character codes (such as A) precede higher
character codes (such as B).
■ The sort places identical values adjacent to each other but in no particular order.
■ The sort is string-based, which means that elements are converted to strings before they
are compared (for example, 10 precedes 3 because the string
"1" has a lower character
code than the string
"3" has).