Jump to content

How to use Arrays in ActionScript 3.0

0
  chco's Photo
Posted Dec 08 2010 01:38 PM

The following excerpt from Learning ActionScript 3.0, Second Edition gives a detailed look at working with arrays.
Basic variables can contain only one value. If you set a variable to 1 and then set that same variable to 2 in the following line of code, the value would be reassigned, and the value of the variable would be 2.

However, there are times when you need one variable to contain more than one value. Think of a hypothetical set of groceries, including 50 items. The standard variable approach to this problem would be to define 50 variables and populate each with a grocery item. That is the equivalent of 50 pieces of paper, each with one grocery item written on its face. This is unwieldy and can be created only at authoring time—at which point the process is fixed—and you’d have to recall and manage all variable names every time you wanted to access the grocery items.

In real life, you handle the problem by writing a list of 50 grocery items on one piece of paper. You can add to the list while at the store and cross each item off once it is acquired, and you only have to manage one piece of paper. In ActionScript, you handle the problem by creating an array, the code equivalent of that sheet of paper.

Creating an array is quite easy. Like many objects in ActionScript 3.0, you can create an array using the new keyword—either prepopulating the array with a comma-separated list of items, or as an empty array that you intend to populate at runtime. You can also create an array by wrapping your list of items in brackets. Creating an empty array with brackets requires only an empty set of brackets. Both techniques are illustrated here:

var needToBuy:Array = new Array("eggs", "flour", "milk");
var impulseItems:Array = new Array();

var needToBuy2:Array = ["eggs", "flour", "milk"];
var impulseItems2:Array = [];


An array of comma-separated values is called a linear array because it contains a series of items in linear order. Whether the array is prepopulated or empty, you can add to, or remove from, the array at runtime. For example, you can add a value to an array using the push() method, which pushes the value into the array at the end.

The push() method is a handy way to add something to an array because it also tells you how long the new array is, and you can choose to use that information or ignore it. In the following example, the second line of code uses push() without any regard for the feedback the method returns. All that matters is adding the item to the end of the array. The second time push() is used, however, the entire statement is placed inside a trace(). As a result, when push() returns a value of 2 to indicate that there are now two items in the array, that value will be traced. Finally, the resulting array is displayed in the last executed instruction.

var cake:Array = new Array();
cake.push("sugar");
trace(cake);
// sugar appears in the Output panel
trace(cake.push("vanilla"));
// 2 appears in the Output panel
trace(cake);
// sugar,vanilla appears in the Output panel


You can remove an item from the end of an array in a similar manner, using the pop() method. This method also returns a value that you may wish to use but, instead of returning the new length of the array, it returns the item removed from the array.

The next code passage continues the previous example, in which the last value of cake was “sugar, vanilla”. The first line removes the last item in the array and, because it does so from within the trace() statement, the removed item appears in the Output panel. Finally, the entire array is then traced.

trace(cake.pop());
// vanilla appears in the Output panel
trace(cake);
// the final one-item array, sugar, is traced


Note: Methods (like push() and pop()) are added to the end of objects (the cake variable) with a dot separating the two words. This is the syntax used to navigate the ActionScript object model, and is sometimes referred to as dot syntax or dot notation. This describes a parent-child relationship among the objects.

Consider an example where you may wish to check the width of a movie clip that is inside another movie clip. The first, or most senior item in this familial chain is the container movie clip, or parent. Let’s call it mc1. A reference to the child clip nested inside, called mc2 in this example, follows, and the width property concludes the statement:

mc1.mc2.width;


You can add values to or retrieve values from locations within the array by using brackets and including the index, or position, of the array item you need. To do so, you must understand that ActionScript uses what are called zero-based arrays. This means that the first value is at position 0, the second is at position 1, the next at position 2, and so on. As an example, to retrieve the existing third value from an array, you must request the item at index 2:

var newArray:Array = ["chocolate", "lemon", "red velvet"];
trace(newArray[2]);
//"red velvet" appears in the Output panel


To determine the number of items in an array, use the length property:

trace(newArray.length);
//"3" appears in the Output panel


You can also create arrays inside arrays. These are typically called multidimensional arrays and are used to create multiple levels of data. A typical database is a multidimensional array because it is a list of records (such as users), each of which contains fields (such as name, phone, email). If such a database had three records, it would be equivalent to one array of three arrays.

Creating this arrangement is as simple as using an inner array as a value for one of the indices of the outer array. You can do this at the outset, or add it using push()—both of which are demonstrated here:

var mdArray1:Array = ["a", "b", ["c", "d"]];
var mdArray2:Array = ["e", "f"];
mdArray2.push(["g", "h"]);


To access values in a multidimensional array, you must use multiple brackets to go into the nested arrays. For instance, continuing the prior example to retrieve the first item in the array mdArray1, you need only the standard single bracket syntax:

trace(mdArray1[0]);
//traces "a" to the Output panel


However, to access the values in the nested array requires two components. First, you must identify the nested array as the third item of mdArray1 (at index 2). Then you must reference the item within that nested array with another pair of brackets. So, to retrieve “c”, which is the first item in the nested array, the syntax is as follows:

trace(mdArray1[2][0]);
//traces "c" to the Output panel


This makes sense, if you think about it in steps, because not only is mdArray1 an array requiring bracket syntax to retrieve an item therein, but mdArray1[2] is also an array requiring its own brackets to retrieve an item.

Note: There is another kind of array, called an associative array, which is often used interchangeably with custom objects.

Learning ActionScript 3.0

Learn more about this topic from Learning ActionScript 3.0, 2nd Edition.

If you're new to ActionScript 3.0, or want to enhance your skill set, this bestselling book is the ideal guide. Designers, developers, and programmers alike will find Learning ActionScript 3.0 invaluable for navigating ActionScript 3.0's learning curve. You'll learn the language by getting a clear look at essential topics such as logic, event handling, displaying content, classes, and much more. Updated for Flash Professional CS5, this revised and expanded edition delivers hands-on exercises and full-color code samples to help you increase your abilities as you progress through the book.

See what you'll learn


Tags:
0 Subscribe


0 Replies