Home >
LFFS - 6: ActionScript 3.0 - Arrays
Organizing data into chunks is a fundamental part of our cognitive experience. The ability to understand individual items in terms of their membership within a group saves our brains an immense amount of processing power. Imagine the difficult time you'd have if, when you went to the grocery store, all of the things you needed to pick up were written on separate pieces of paper instead of on a nicely organized list. You could still get your shopping done, but it would be a real pain to shuffle through all those individual sheets! In addition, you'd have to make sure that all of those sheets really actually contained things you needed to pick up from the store, and not perhaps, things that you already had in your refrigerator. In other words, using an organized system that groups items together into meaningful lists saves you a lot of time and effort.
Thankfully, ActionScript, like almost every programming language, has a convenient way of organizing data. By using what's known as an "array" we can easily group together a number of items that can be collectively referenced by some code within our application. An array is an object that groups multiple objects together into an organized group. The Array class in ActionScript, like all classes, defines the methods and properties that objects derived from it will have. In this installment, we introduce a few of the many ways in which you can work with arrays in ActionScript 3.0.
By far, the most common type of array in ActionScript is the indexed array, and that's the type of array we are focusing on here. ActionScript also has the idea of associative arrays. We'll look at associative arrays in a later post. An indexed array stores a group of objects that are organized in terms of their position, or index. For example, an indexed array may include a list of names, such as: "Ana", "Kate", "John". These names are examples of String objects: "Ana", "Kate", and "John", respectively, where Ana occupies the first position, Kate the second, and John the third. ActionScript starts counting indexes at "0", however, so "Ana" would have an index==0, "Kate"'s index==1, and "John"'s index==2. We can create an array by using the following syntax:
var arrayName : Array = new Array();
This syntax would yield an Array object with the following qualities: a variable named "arrayName", which is an Array, and is equal to an instantiation of the Array class (an object from the Array class). This array doesn't have any contents, however, because its parentheses are empty. (The contents of an array, known as its "elements", are initialized within its parentheses). It's possible to create an array of undefined values by simply using a single integer for an array's argument, as in:
var arrayName : Array = new Array( 5 );
This syntax creates an array with five elements, each of which with an undefined value.
If we want to create an array containing the names we discussed previously, we would simply type:
var arrayName : Array = new Array( "Ana", "Kate", "John" );
This creates an array of 3 elements, all of which are Strings. The elements of an array are separated by commas, and as you probably already know, a String is recognized as being surrounded by a set of quotes.
It's also possible to define an array using literal syntax. To declare the above array literally, we would type:
var arrayName : Array = [ "Ana", "Kate", "John" ];
Note the use of brackets instead of parentheses in the array literal definition. The brackets are known as "array access operators", and they can be used to create an array, or to access the elements of an array.
Understanding an Actual Code Example
Let's now take our knowledge of indexed arrays and extend it to an MXML application that traces the names of the members of the T.V. show "Lost" in a few different ways. For those unfamiliar with the term "trace" in this context, we're referring to a global function in ActionScript 3.0 that displays expressions while running an application in debug mode. The application in our example relies on trace functions to display the various outcomes of our methods as they apply to our array. The "Learning Flex From Scratch" series hasn't covered MXML syntax yet, so just keep in mind that the ActionScript code can be written inside a script tag in an MXML file. It looks like this:
<mx:Script>
<![CDATA[
// ActionScript code goes here
]]>
</mx:Script>
The first ActionScript code we run across is the "init()" function. Again, we haven't covered MXML in any detail yet, so for now let's just know that whenever an event called "initialize" is fired off by the application, the "init()" function is called. The opening tag of the MXML application declares that the "initialize" event should call the "init() method by using this syntax:
initialize="init()"
Within the "init()" function are six different parameters with trace functions that ask Flex Builder to trace the array of names in different ways. It may help to scroll down to the bottom of the ActionScript code to check out the list of names. That's the array we're working with, and we'll be referring to it from here on out:
private function init() : void
{
traceCharacterNames();
traceCharacterNamesUpperCase();
traceCharacterNamesExcept( "Hurley" );
traceCharacterNamesExcept( "Jack" );
traceCharacterNamesExcept( "Sun" );
traceCharacterNamesReverse();
}
Our application has three functions with identical names as the trace functions in the parameters of the "init()" function. The first:
private function traceCharacterNames() : void
{
trace( "traceCharacterNames()" );
for each ( var name : String in __names )
{
trace( " - " + name );
}
trace( "" );
}
This function traces the names of the array in order. By studying the method body, we can see that the phrase "traceCharacterNames()" should be displayed when the application is run in debug mode. Following that, we have a "for each in" loop that says "for each String object in our array, trace, two spaces, a dash(-), another space and then the name". There's also another line of code following that one that simply says "trace an empty string after you've traced that other stuff". The compiler sees quotation marks and interprets what follows as the start of a String. So by tracing(""), we are simply tracing an empty String, which puts a line break in our displayed results for easier viewing. The traced output looks like this:
traceCharacterNames()
- Kate Austen
- Sayid Jarrah
- Sun Kwon
- Hugo "Hurley" Reyes
- Jack Shephard
- Boone Carlyle
- Ana Lucia Cortez
- Michael Dawson
- Nikki Fernandez
- James "Sawyer" Ford
- Jin Kwon
- Libby
- Claire Littleton
- Walt Lloyd
- John Locke
- Charlie Pace
- Paulo
- Shannon Rutherford
- Eko Tunde
Our next instance method:
private function traceCharacterNamesUpperCase() : void
{
trace( "traceCharacterNamesUpperCase()" );
for each ( var name : String in __names )
{
trace( " - " + name.toUpperCase() );
}
trace( "" );
}
The traced output of this method displays all of the names of the array in capital letters. This is achieved by the "for each in" loop in the method body. This example uses what's known as "dot syntax" to call a special method of the String class that displays all of the values in a String as capital letters. Dot syntax allows you to access the properties and methods of an object by coding the instance name of an object, (in this case "name" is the instance name of the String class), followed by a "dot" operator, and then the name of the property or method, (in our case, the "toUpperCase" method). The traced output of this method looks like this:
traceCharacterNamesUpperCase()
- KATE AUSTEN
- SAYID JARRAH
- SUN KWON
- HUGO "HURLEY" REYES
- JACK SHEPHARD
- BOONE CARLYLE
- ANA LUCIA CORTEZ
- MICHAEL DAWSON
- NIKKI FERNANDEZ
- JAMES "SAWYER" FORD
- JIN KWON
- LIBBY
- CLAIRE LITTLETON
- WALT LLOYD
- JOHN LOCKE
- CHARLIE PACE
- PAULO
- SHANNON RUTHERFORD
- EKO TUNDE
To understand what's going on in the next method, we'll need to explain some language elements that might be unfamiliar. The first is the use of an "escape character"(\"). An escape character suppresses the normal meaning of the character following the backslash. For example, since quotes(") are used to signify the start or end of a String object, in order to display quotes within a String we need to tell the compiler to ignore the standard meaning of ("). Consider this String: "I "sort of" understand this". In order to include the quotes around the phrase "sort of" when traced, we use an escape character before each of the quotes surrounding the phrase. It might look something like this:
var comprehendStuff : String ="I \"sort of\" understand this";
Without the backslash, the compiler would see the quotes, and in the case of the first one, think that a full String was "I". Then, it would think that the second quote was the start of another String -"understand this". The escape character in our MXML application allows for a String to be displayed surrounded by quotation marks:
trace( "traceCharacterNamesExcept( \"" + exception + "\" )" );
The second thing we need to explain is the concatenation character(+). Concatenation means to "join together". What our example says is that the String "traceCharacterNamesExcept(\"" should be concatenated with the exception name, and then with another String "\")". The three Strings joined together will give us a traced output of "traceCharacterNamesExcept("Hurley").
Finally, this method introduces another method of the String class-indexOf(). The indexOf() method searches through a String for a given value, and if found, returns the index of that value. If no value is found, indexOf() returns -1.
The code for this method:
private function traceCharacterNamesExcept( exception : String ) : void
{
trace( "traceCharacterNamesExcept( \"" + exception + "\" )" );
for each ( var name : String in __names )
{
if ( name.indexOf(exception) == -1 )
{
trace( " - " + name );
}
}
trace( "" );
}
This method says to trace the variable called exception, which is a String. Looking back at the init function's parameters, we can see that three of the functions listed there have Strings listed as arguments-"Hurley", "Jack", and "Sun". These are the names that "exception" refers to.
Next, within the method body we have our trace function:
trace( "traceCharacterNamesExcept( \"" + exception + "\" )" );
This tells the Flash Player to trace the function name plus the exception name in quotes. The escape characters allow for the inclusion of the quotation, among other things, marks in the traced output.
Then, the for each in loop says what else to trace. By using the indexOf() method of the String class, the method searches through all of the names in the array for the exception name. Remember, if indexOf() doesn't find what it's looking for, it returns -1. As a condition of our "for each in" loop, if the returned value is -1, then the names in the array will be traced.
So what happens is, the function name is displayed with the exception name in quotes. Then, when our indexOf() method searches the array for the exception name and doesn't find it, it traces it because it would have returned an index of -1. When the the indexOf() method hits a match to an exception name, the returned value isn't -1, so, according to our loop, the name isn't traced with the others. Here's what the traced output looks like:
traceCharacterNamesExcept( "Hurley" )
- Kate Austen
- Sayid Jarrah
- Sun Kwon
- Jack Shephard
- Boone Carlyle
- Ana Lucia Cortez
- Michael Dawson
- Nikki Fernandez
- James "Sawyer" Ford
- Jin Kwon
- Libby
- Claire Littleton
- Walt Lloyd
- John Locke
- Charlie Pace
- Paulo
- Shannon Rutherford
- Eko Tunde
traceCharacterNamesExcept( "Jack" )
- Kate Austen
- Sayid Jarrah
- Sun Kwon
- Hugo "Hurley" Reyes
- Boone Carlyle
- Ana Lucia Cortez
- Michael Dawson
- Nikki Fernandez
- James "Sawyer" Ford
- Jin Kwon
- Libby
- Claire Littleton
- Walt Lloyd
- John Locke
- Charlie Pace
- Paulo
- Shannon Rutherford
- Eko Tunde
traceCharacterNamesExcept( "Sun" )
- Kate Austen
- Sayid Jarrah
- Hugo "Hurley" Reyes
- Jack Shephard
- Boone Carlyle
- Ana Lucia Cortez
- Michael Dawson
- Nikki Fernandez
- James "Sawyer" Ford
- Jin Kwon
- Libby
- Claire Littleton
- Walt Lloyd
- John Locke
- Charlie Pace
- Paulo
- Shannon Rutherford
- Eko Tunde
Our last instance method within the example introduces two ways of arranging the elements of an array. By utilizing the "split()", "join()", and "reverse()" methods, we can display our character names in reverse. The following statement:
trace( "- " + name.split( "" ).reverse().join( "" ) );
uses dot syntax to chain the three methods together. We invoke the "split()" method to separate the String name into an array of sub-Strings, separated into individual characters, as per the argument-(""). For example, "Flex".split("") would return: [ "F", "l", "e","x" ]. Next, the index order of the array is reversed by calling the "reverse()" method. And finally, the "join()" method returns an individual String from the array of sub-Strings. The resulting traced output looks like this:
traceCharacterNamesReverse()
- netsuA etaK
- harraJ diyaS
- nowK nuS
- seyeR "yelruH" oguH
- drahpehS kcaJ
- elylraC enooB
- zetroC aicuL anA
- noswaD leahciM
- zednanreF ikkiN
- droF "reywaS" semaJ
- nowK niJ
- ybbiL
- notelttiL erialC
- dyolL tlaW
- ekcoL nhoJ
- ecaP eilrahC
- oluaP
- drofrehtuR nonnahS
- ednuT okE
Future installments will cover more involved use of arrays, including associative arrays, and multidimensional arrays, as we begin to build applications in Flex. Before we get to that, however, we're going to cover MXML basics so that we can get started with Flex Builder.
<?xml version="1.0" encoding="utf-8"?>
<!--=============================================================================================-->
<!-- -->
<!-- This is a sample application that is part of the ORiley Inside RIA series "Learning Flex -->
<!-- from Scratch" by Adam Flater and Scott Sheridan. ( www.insideRIA.com ) -->
<!-- -->
<!-- This sample should be run in Adobe Flex Builder 3 under debug mode. The results of -->
<!-- execution can be observed in the "Console" view. -->
<!-- -->
<!--=============================================================================================-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
initialize="init()">
<mx:Script>
<![CDATA[
/**
* @private
* Called by the initialize event.
*/
private function init() : void
{
traceCharacterNames();
traceCharacterNamesUpperCase();
traceCharacterNamesExcept( "Hurley" );
traceCharacterNamesExcept( "Jack" );
traceCharacterNamesExcept( "Sun" );
traceCharacterNamesReverse();
}
/**
* @private
* Traces the Strings in the Array __names.
*/
private function traceCharacterNames() : void
{
trace( "traceCharacterNames()" );
for each ( var name : String in __names )
{
trace( " - " + name );
}
trace( "" );
}
/**
* @private
* Traces the Strings in the Array __names in upper case.
*/
private function traceCharacterNamesUpperCase() : void
{
trace( "traceCharacterNamesUpperCase()" );
for each ( var name : String in __names )
{
trace( " - " + name.toUpperCase() );
}
trace( "" );
}
/**
* @private
* Traces the Strings in the Array __names except the name 'exception'.
*/
private function traceCharacterNamesExcept( exception : String ) : void
{
trace( "traceCharacterNamesExcept( \"" + exception + "\" )" );
for each ( var name : String in __names )
{
if ( name.indexOf(exception) == -1 )
{
trace( " - " + name );
}
}
trace( "" );
}
/**
* @private
* Traces the Strings in the Array __names spelled backwards
*/
private function traceCharacterNamesReverse() : void
{
trace( "traceCharacterNamesReverse()" );
for each ( var name : String in __names )
{
trace( "- " + name.split( "" ).reverse().join( "" ) );
}
trace( "" );
}
/**
* @private
* An array of character names from the tv show Lost
*/
private var __names : Array = [
'Kate Austen', 'Sayid Jarrah', 'Sun Kwon', 'Hugo "Hurley" Reyes', 'Jack Shephard', 'Boone Carlyle', 'Ana
Lucia Cortez', 'Michael Dawson', 'Nikki Fernandez', 'James "Sawyer" Ford', 'Jin Kwon', 'Libby', 'Claire
Littleton', 'Walt Lloyd', 'John Locke', 'Charlie Pace', 'Paulo', 'Shannon Rutherford', 'Eko Tunde'
];
]]>
</mx:Script>
</mx:Application>
Glossary of Terms
Array A data structure that consist of a group of elements.
dot syntax The practice of referring to an object's methods or properties by stating the object's instance name, followed by a dot (.) character, and then the desired method or property name.
element An individual object within an array.
index The ordered position of an object within an array. In ActionScript 3.0, the index of an object in the first position is "zero".
indexed array The most common type of array in ActionScript 3.0, an indexed array organizes its contents according to their position, starting at position zero, and continuing up from there.
indexOf() A method in the Array class that searches an array for a particular value. If an indexOf method finds no value, it returns an index of "-1".
join() A method of the Array class that combines the elements of an array into a single String.
reverse() A method of the Array class that reverses an elements index position in an array.
split() A method of the String class that splits the elements of an array at an assigned delimiting point.
Next: LFFS - 7: Helpful Resources For Learning Flex (part one)




Facebook Application Development
Thanks alot for this great tutorial!
Thanks for the very detailed info in Arrays! I can definitely learn from this! I am working on a widget that has two text fields. One is an input text box, and the one below it is a dynamic text box. I am trying to make code that will read the text from the input box and then grab a string from the array based on what is typed.
*If you could help me with this code I would greatly appreciate it.