Skip to any available Digital Media Help Center chapter of ActionScript 3.0 Cookbook: |
Arrays are essential to successful ActionScript programming.
An array provides a way of grouping related data together, and then organizing and processing that data. The concept of an array should not be foreign to you. In fact, the concept is used all the time in everyday life. You can view a simple grocery list or to-do list as an array. Your address book is an array containing people's names, addresses, birthdates, and so on. Libraries keep track of books using an indexing system whereby each book becomes, conceptually, an element in a library's array.
In ActionScript, there are two kinds of arrays: integer-indexed and associative. Both array types group related data, but they use different means of accessing the data.
index (i.e., element number), starting from 0. Each element occupies a numbered slot in the array. Integer-indexed arrays are ideal for sets of data that you want to work with in sequential order.Integer-indexed arrays are the focus of the majority of the recipes in this chapter, and unless otherwise specified, the term "array" refers to an integer-indexed array.
Of course, before you can use an array, you first need to know how to create one. There are two ways to construct a new array in ActionScript: with the constructor function or as an array literal. All arrays are members of the Array class. You can use the Array( ) constructor function to instantiate new array objects in one of three ways:
// Create an empty array. var array:Array = new Array(); // Create an array with elements undefined elements. var array:Array = new Array(elements); // Create an array with specified elements. var array:Array = new Array(element0,...elementN);
The array literal notation also creates a new array, but without using the constructor function. Literal notation is convenient for specifying elements at the time of creation, such as:
var letters:Array = ["a", "b", "c"];
Some methods of the Array class modify the existing array on which the method is called, and others return a new array (offering an indirect way to create arrays).
You retrieve and set array elements using the array-access operator ( square brackets) and the index of the element you wish to get or set, for example:
// Set the fifth element of the array called items to "apples"
// (array indexes start at 0).
items[4] = "apples";
// Display the fifth element in the Output window.
trace(items[4]); // Displays: apples
ActionScript doesn't care what kind of values you store in an array. You can store strings, numbers, Booleans, or references to any kind of objects. And, unlike stricter programming languages, you can even store different datatypes in a single array. For example, this array stores a string, an integer, a Boolean, and an object:
var data:Array = ["a", 2, true, new Object()];
Unlike many languages, ActionScript doesn't force you to specify the number of elements in an array when it is declared.
You want to add elements to an existing array.
Use the push( ) method to append elements to the end of an array; use the unshift( ) method to insert elements at the beginning of an array.
This excerpt is from ActionScript 3.0 Cookbook. Well before Ajax and Windows Presentation Foundation, Macromedia Flash provided the first method for building "rich" web pages. Now, Adobe is making Flash a full-fledged development environment, and learning ActionScript 3.0 is key. That's a challenge for even the most experienced Flash developer. This Cookbook offers more than 300 solutions to solve a wide range of coding dilemmas, so you can learn to work with the new version right away.
You append elements to the end of an existing array using the Array.push( ) method, passing it one or more values to be appended:
var array:Array = new Array();
array.push("val 1", "val 2");
You can also append a single element by using the array's length property as the index. Because ActionScript array indexes are zero-indexed (meaning that the first index is 0, not 1), the last element is at an index of Array .length - 1. Therefore, putting an element at index Array .length creates a new element right after the current last element; for example:
array[array.length] = "val 3";
If you set an element with an index that doesn't exist, the array extends itself to include the necessary number of elements automatically. If there are any intervening elements, they are initialized to undefined. For example, letters will contain the elements ["a", "b", "c", undefined, undefined, "f"] after you execute the following statements:
var letters:Array = ["a", "b", "c"]; letters[5] = "f";
Appending elements onto an array is common when you want to build an array incrementally or when you want to store the history of a user's actions for the purpose of implementing a back button or history feature.
To add elements to the beginning of an array, use the unshift( ) method. This shifts the existing elements up by one index position, and inserts the new element at index 0:
// Create an array with four elements:
// "a", "b", "c", and "d".
var letters:Array = new Array( );
letters.push("a", "b", "c", "d");
// Add "z" to the beginning of the array. This shifts all
// the other elements so the value of "a" moves from
// index 0 to index 1, etc.
letters.unshift("z");
// Display the results by looping through the elements.
// See Recipe 5.2.
for (var i:int = 0; i < letters.length; i++) {
trace(letters[i]);
}
Should you add elements to the beginning or the end of an array? That generally depends on how you intend to access or remove the elements at a later time. For example, if you want to access items in last in, first out (LIFO) order, you might use Array.push( ) to add elements to an array and Array.pop( ) to remove the elements in reverse order.
Recipe 5.2
You want to access each element of an array in sequential order.
Use a for loop that increments an index variable from 0 until it reaches Array. length. Use the index to access each element in turn.
To access the values stored in the elements of an array, loop through the array's elements using a for loop. Because the first index of an array is 0, the index variable in the for statement should start at 0. The last index of an array is always 1 less than the length property of that array. Within the for statement, use the loop index variable within square brackets to access array elements. For example:
var letters:Array = ["a", "b", "c"];
for (var i:int = 0; i < letters.length; i++) {
// Display the elements in the Output panel.
trace("Element " + i + ": " + letters[i]);
}
The looping index variable (i in the example code) should range from 0 to one less than the value of the length property. Remember that the last index of an array is always one less than its length.