This guide is protected under copyright law, furnished for informational use only, is subject to change without notice, and should not be construed as a
commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear
in the informational content contained in this guide.
This guide is licensed for use under the terms of the Creative Commons Attribution Non-Commercial 3.0 License. This License allows users to copy, distribute,
and transmit the guide for noncommercial purposes only so long as (1) proper attribution to Adobe is given as the owner of the guide; and (2) any reuse or
distribution of the guide contains a notice that use of the guide is governed by these terms. The best way to provide notice is to include the following link. To
view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/
Adobe, the Adobe logo, Acrobat, Acrobat Capture, Acrobat Connect, Acrobat Messenger, Acrobat 3D Capture, ActionScript, ActiveTest, Adobe ActionSource,
Adobe AIR, Adobe AIR logo, Adobe Audition, Adobe Caslon, Adobe Connect, Adobe DataWarehouse, Adobe Dimensions, Adobe Discover, Adobe Financial
Services, Adobe Garamond, Adobe Genesis, Adobe Griffo, Adobe Jenson, Adobe Kis, Adobe OnLocation, Adobe Originals logo, Adobe PDF logo, Adobe
Premiere, AdobePS, Adobe SiteSearch, Adobe Type Manager, Adobe Wave, Adobe Wave logo , Adobe WebType, Adobe Wood Type, After Effects, AIR , Alexa,
Andreas, Arno, ATM, Authorware, Balzano, Banshee, Benson Scripts, Better by Adobe. , Bickham Script, Birch, Blackoak, Blue Island, Brioso, BusinessCatalyst,
Buzzword, Caflisch Script, Cairngorm, Calcite, Caliban, Captivate, Carta, Chaparral, Charlemagne, Cheq, Classroom in a Book, ClickMap, Co-Author,
ColdFusion, ColdFusion Builder, Conga Brava, Contribute, Copal, Coriander, Cottonwood, Creative Suite, Critter, Cronos, CS Live, Custom Insight,
CustomerFirst, Cutout, Digital Pulse, Director, Distiller, DNG logo, Dreamweaver, DV Rack, Encore, Engaging beyond the Enterprise, ePaper, Ex Ponto,
Fireworks, Flash, Flash logo, Flash Access, Flash Access logo, Flash Builder, Flash Cast , FlashCast, Flash Catalyst, FlashHelp, Flash Lite, Flash on., FlashPaper,
Flash Platform Services logo , Flex, Flex Builder, Flood, Font Folio, Frame , FrameCenter, FrameConnections, FrameMaker, FrameManager, FrameViewer,
FreeHand, Fusaka, Galahad, Giddyup, Giddyup Thangs, GoLive, GoodBarry, Graphite, HomeSite, HBX, HTML Help Studio, HTTP Dynamic Streaming logo ,
Hypatia, Illustrator, ImageReady, Immi 505, InCopy, InDesign, Ironwood, Jimbo, JRun, Juniper, Kazuraki, Kepler, Kinesis, Kozuka Gothic, Kozuka Mincho,
Kuler, Leander Script, Lens Profile Creator logo , Lightroom, Lithos, LiveCycle, Macromedia, Madrone, Mercado, Mesquite, Mezz, Minion, Mojo, Montara,
Moonglow, MXML, Myriad, Mythos, Nueva, Nyx, 1-Step RoboPDF, Omniture, Open Screen Project, Open Source Media Framework logo, OpenType logo,
Ouch!, Ovation, PageMaker, PageMaker Portfolio, PDF JobReady, Penumbra, Pepperwood, Photoshop, Photoshop logo, Pixel Bender, Poetica, Ponderosa,
Poplar, Postino, PostScript, PostScript logo, PostScript 3, PostScript 3i, Powered by XMP, Prana, PSPrinter, Quake, Rad, Reader, Real-Time Analytics, Reliq,
RoboEngine, RoboHelp, RoboHTML, RoboLinker, RoboPDF, RoboScreenCapture, RoboSource Control, Rosewood, Roundtrip HTML, Ryo, Sanvito, Sava,
Scene7, See What’s Possible , Script Teaser, Shockwave, Shockwave Player logo, Shuriken Boy, Silentium, Silicon Slopes, SiteCatalyst, SiteCatalyst NetAverages,
Software Video Camera, Sonata, Soundbooth, SoundEdit, Strumpf, Studz, Tekton, Test&Target, 360Code, Toolbox, Trajan, TrueEdge, Type Reunion, Ultra,
Utopia, Vector Keying, Version Cue, VirtualTrak, Visual Call, Visual Communicator, Visual Sciences, Visual Sensor, Visual Server, Viva, Voluta , Warnock,
Waters Titling, Wave , Willow, XMP logo, Zebrawood are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or
other countries.
Android is a trademark of Google Inc. ActiveX and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and
other countries. Macintosh is a trademark of Apple Inc., registered in the United States and other countries. Java is a trademark or registered trademark of Sun
Microsystems, Inc. in the United States and other countries. All other trademarks are the property of their respective owners.
Updated Information/Additional Third Party Code Information available at http://www.adobe.com/go/thirdparty.
Portions include software under the following terms:
This product includes software developed by the Apache Software Foundation (http://www.apache.org/).
MPEG Layer-3 audio compression technology licensed by Fraunhofer IIS and Thomson Multimedia (http://www.mp3licensing.com).
This software is based in part on the work of the Independent JPEG Group.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
This product contains either BSAFE and/or TIPEM software by RSA Security, Inc.
Sorenson Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA
Notice to U.S. Government End Users: The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of
“Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202,
as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and
Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights
as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.
Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section 402
of the Vietnam Era Veterans Readjustment Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the
regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
Chapter 64: SQL error detail messages, ids, and arguments
xiii
Last updated 3/21/2011
Chapter 1: Working with dates and times
Flash Player 9 and later, Adobe AIR 1.0 and later
Timing might not be everything, but it's usually a key factor in software applications. ActionScript 3.0 provides
powerful ways to manage calendar dates, times, and time intervals. Two main classes provide most of this timing
functionality: the Date class and the new Timer class in the flash.utils package.
Dates and times are a common type of information used in ActionScript programs. For instance, you might need to
know the current day of the week or to measure how much time a user spends on a particular screen, among many
other possibilities. In ActionScript, you can use the Date class to represent a single moment in time, including date and
time information. Within a Date instance are values for the individual date and time units, including year, month, date,
day of the week, hour, minutes, seconds, milliseconds, and time zone. For more advanced uses, ActionScript also
includes the Timer class, which you can use to perform actions after a certain delay or at repeated intervals.
More Help topics
Date
1
flash.utils.Timer
Managing calendar dates and times
Flash Player 9 and later, Adobe AIR 1.0 and later
All of the calendar date and time management functions in ActionScript 3.0 are concentrated in the top-level Date
class. The Date class contains methods and properties that let you handle dates and times in either Coordinated
Universal Time (UTC) or in local time specific to a time zone. UTC is a standard time definition that is essentially the
same as Greenwich Mean Time (GMT).
Creating Date objects
Flash Player 9 and later, Adobe AIR 1.0 and later
The Date class boasts one of the most versatile constructor methods of all the core classes. You can invoke it four
different ways.
First, if given no parameters, the Date() constructor returns a Date object containing the current date and time, in
local time based on your time zone. Here’s an example:
var now:Date = new Date();
Second, if given a single numeric parameter, the Date() constructor treats that as the number of milliseconds since
January 1, 1970, and returns a corresponding Date object. Note that the millisecond value you pass in is treated as
milliseconds since January 1, 1970, in UTC. However, the Date object shows values in your local time zone, unless you
use the UTC-specific methods to retrieve and display them. If you create a new Date object using a single milliseconds
parameter, make sure you account for the time zone difference between your local time and UTC. The following
statements create a Date object set to midnight on the day of January 1, 1970, in UTC:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
// gets a Date one day after the start date of 1/1/1970
var startTime:Date = new Date(millisecondsPerDay);
Third, you can pass multiple numeric parameters to the Date() constructor. It treats those parameters as the year,
month, day, hour, minute, second, and millisecond, respectively, and returns a corresponding Date object. Those input
parameters are assumed to be in local time rather than UTC. The following statements get a Date object set to midnight
at the start of January 1, 2000, in local time:
var millenium:Date = new Date(2000, 0, 1, 0, 0, 0, 0);
Fourth, you can pass a single string parameter to the Date() constructor. It will try to parse that string into date or
time components and then return a corresponding Date object. If you use this approach, it’s a good idea to enclose the
Date() constructor in a try..catch block to trap any parsing errors. The Date() constructor accepts a number of
different string formats (which are listed in the
ActionScript 3.0 Reference for the Adobe Flash Platform). The
following statement initializes a new Date object using a string value:
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");
If the Date() constructor cannot successfully parse the string parameter, it will not raise an exception. However, the
resulting Date object will contain an invalid date value.
2
Getting time unit values
Flash Player 9 and later, Adobe AIR 1.0 and later
You can extract the values for various units of time within a Date object using properties or methods of the Date class.
Each of the following properties gives you the value of a time unit in the Date object:
• The fullYear property
• The month property, which is in a numeric format with 0 for January up to 11 for December
• The date property, which is the calendar number of the day of the month, in the range of 1 to 31
• The day property, which is the day of the week in numeric format, with 0 standing for Sunday
• The hours property, in the range of 0 to 23
• The minutes property
• The seconds property
• The milliseconds property
In fact, the Date class gives you a number of ways to get each of these values. For example, you can get the month
value of a Date object in four different ways:
• The month property
• The getMonth() method
• The monthUTC property
• The getMonthUTC() method
All four ways are essentially equivalent in terms of efficiency, so you can use whichever approach suits your
application best.
The properties just listed all represent components of the total date value. For example, the milliseconds property
will never be greater than 999, since when it reaches 1000 the seconds value increases by 1 and the milliseconds
property resets to 0.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
If you want to get the value of the Date object in terms of milliseconds since January 1, 1970 (UTC), you can use
getTime() method. Its counterpart, the setTime() method, lets you change the value of an existing Date
the
object using milliseconds since January 1, 1970 (UTC).
Performing date and time arithmetic
Flash Player 9 and later, Adobe AIR 1.0 and later
You can perform addition and subtraction on dates and times with the Date class. Date values are kept internally in
terms of milliseconds, so you should convert other values to milliseconds before adding them to or subtracting them
from Date objects.
If your application will perform a lot of date and time arithmetic, you might find it useful to create constants that hold
common time unit values in terms of milliseconds, like the following:
public static const millisecondsPerMinute:int = 1000 * 60;
public static const millisecondsPerHour:int = 1000 * 60 * 60;
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
Now it is easy to perform date arithmetic using standard time units. The following code sets a date value to one hour
from the current time using the
getTime() and setTime() methods:
3
var oneHourFromNow:Date = new Date();
oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour);
Another way to set a date value is to create a new Date object using a single milliseconds parameter. For example, the
following code adds 30 days to one date to calculate another:
// sets the invoice date to today's date
var invoiceDate:Date = new Date();
// adds 30 days to get the due date
var dueDate:Date = new Date(invoiceDate.getTime() + (30 * millisecondsPerDay));
Next, the millisecondsPerDay constant is multiplied by 30 to represent 30 days’ time and the result is added to the
invoiceDate value and used to set the dueDate value.
Converting between time zones
Flash Player 9 and later, Adobe AIR 1.0 and later
Date and time arithmetic comes in handy when you want to convert dates from one time zone to another. So does the
getTimezoneOffset() method, which returns the value in minutes by which the Date object’s time zone differs from
UTC. It returns a value in minutes because not all time zones are set to even-hour increments—some have half-hour
offsets from neighboring zones.
The following example uses the time zone offset to convert a date from local time to UTC. It does the conversion by
first calculating the time zone value in milliseconds and then adjusting the Date value by that amount:
// creates a Date in local time
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");
// converts the Date to UTC by adding or subtracting the time zone offset
var offsetMilliseconds:Number = nextDay.getTimezoneOffset() * 60 * 1000;
nextDay.setTime(nextDay.getTime() + offsetMilliseconds);
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Controlling time intervals
Flash Player 9 and later, Adobe AIR 1.0 and later
When you develop applications using Adobe Flash CS4 Professional, you have access to the timeline, which provides
a steady, frame-by-frame progression through your application. In pure ActionScript projects, however, you must rely
on other timing mechanisms.
Loops versus timers
Flash Player 9 and later, Adobe AIR 1.0 and later
In some programming languages, you must devise your own timing schemes using loop statements like for or
do..while.
Loop statements generally execute as fast as the local machine allows, which means that the application runs faster on
some machines and slower on others. If your application needs a consistent timing interval, you need to tie it to an
actual calendar or clock time. Many applications, such as games, animations, and real-time controllers, need regular,
time-driven ticking mechanisms that are consistent from machine to machine.
4
The ActionScript 3.0 Timer class provides a powerful solution. Using the ActionScript 3.0 event model, the Timer class
dispatches timer events whenever a specified time interval is reached.
The Timer class
Flash Player 9 and later, Adobe AIR 1.0 and later
The preferred way to handle timing functions in ActionScript 3.0 is to use the Timer class (flash.utils.Timer), which
can be used to dispatch events whenever an interval is reached.
To start a timer, you first create an instance of the Timer class, telling it how often to generate a timer event and how
many times to do so before stopping.
For example, the following code creates a Timer instance that dispatches an event every second and continues for 60
seconds:
var oneMinuteTimer:Timer = new Timer(1000, 60);
The Timer object dispatches a TimerEvent object each time the given interval is reached. A TimerEvent object’s event
timer (defined by the constant TimerEvent.TIMER). A TimerEvent object contains the same properties as a
type is
standard Event object.
If the Timer instance is set to a fixed number of intervals, it will also dispatch a timerComplete event (defined by the
constant
Here is a small sample application showing the Timer class in action:
TimerEvent.TIMER_COMPLETE) when it reaches the final interval.
public class ShortTimer extends Sprite
{
public function ShortTimer()
{
// creates a new five-second Timer
var minuteTimer:Timer = new Timer(1000, 5);
// designates listeners for the interval and completion events
minuteTimer.addEventListener(TimerEvent.TIMER, onTick);
minuteTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
// starts the timer ticking
minuteTimer.start();
}
public function onTick(event:TimerEvent):void
{
// displays the tick count so far
// The target of this event is the Timer instance itself.
trace("tick " + event.target.currentCount);
}
public function onTimerComplete(event:TimerEvent):void
{
trace("Time's Up!");
}
}
}
5
When the ShortTimer class is created, it creates a Timer instance that will tick once per second for five seconds. Then
it adds two listeners to the timer: one that listens to each tick, and one that listens for the
timerComplete event.
Next, it starts the timer ticking, and from that point forward, the onTick() method executes at one-second intervals.
The onTick() method simply displays the current tick count. After five seconds have passed, the
onTimerComplete() method executes, telling you that the time is up.
When you run this sample, you should see the following lines appear in your console or trace window at the rate of
one line per second:
tick 1
tick 2
tick 3
tick 4
tick 5
Time's Up!
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Timing functions in the flash.utils package
Flash Player 9 and later, Adobe AIR 1.0 and later
ActionScript 3.0 contains a number of timing functions similar to those that were available in ActionScript 2.0. These
functions are provided as package-level functions in the flash.utils package, and they operate just as they did in
ActionScript 2.0.
FunctionDescription
clearInterval(id:uint):voidCancels a specified setInterval() call.
clearTimeout(id:uint):voidCancels a specified setTimeout() call.
Returns the number of milliseconds that have elapsed since Adobe® Flash® Player
or Adobe
® AIR™ was initialized.
Runs a function at a specified interval (in milliseconds).
Runs a specified function after a specified delay (in milliseconds).
These functions remain in ActionScript 3.0 for backward compatibility. Adobe does not recommend that you use them
in new ActionScript 3.0 applications. In general, it is easier and more efficient to use the Timer class in your
applications.
Date and time example: Simple analog clock
Flash Player 9 and later, Adobe AIR 1.0 and later
A simple analog clock example illustrates these two date and time concepts:
• Getting the current date and time and extracting values for the hours, minutes, and seconds
• Using a Timer to set the pace of an application
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The
SimpleClock application files can be found in the folder Samples/SimpleClock. The application consists of the
following files:
FileDescription
SimpleClockApp.mxml
or
SimpleClockApp.fla
com/example/programmingas3/simpleclock/SimpleClock.asThe main application file.
com/example/programmingas3/simpleclock/AnalogClockFace.asDraws a round clock face and hour, minute, and seconds
The main application file in Flash (FLA) or Flex (MXML).
hands based on the time.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Defining the SimpleClock class
Flash Player 9 and later, Adobe AIR 1.0 and later
The clock example is simple, but it’s a good idea to organize even simple applications well so you could easily expand
them in the future. To that end, the SimpleClock application uses the SimpleClock class to handle the startup and timekeeping tasks, and then uses another class named AnalogClockFace to actually display the time.
Here is the code that defines and initializes the SimpleClock class (note that in the Flash version, SimpleClock extends
the Sprite class instead):
public class SimpleClock extends UIComponent
{
/**
* The time display component.
*/
private var face:AnalogClockFace;
/**
* The Timer that acts like a heartbeat for the application.
*/
private var ticker:Timer;
7
The class has two important properties:
• The face property, which is an instance of the AnalogClockFace class
• The ticker property, which is an instance of the Timer class
The SimpleClock class uses a default constructor. The initClock() method takes care of the real setup work,
creating the clock face and starting the Timer instance ticking.
Creating the clock face
Flash Player 9 and later, Adobe AIR 1.0 and later
The next lines in the SimpleClock code create the clock face that is used to display the time:
/**
* Sets up a SimpleClock instance.
*/
public function initClock(faceSize:Number = 200)
{
// creates the clock face and adds it to the display list
face = new AnalogClockFace(Math.max(20, faceSize));
face.init();
addChild(face);
// draws the initial clock display
face.draw();
The size of the face can be passed in to the initClock() method. If no faceSize value is passed, a default size of 200
pixels is used.
Next, the application initializes the face and then adds it to the display list using the addChild() method inherited
from the DisplayObjectContainer class. Then it calls the
AnalogClockFace.draw() method to display the clock face
once, showing the current time.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Starting the timer
Flash Player 9 and later, Adobe AIR 1.0 and later
After creating the clock face, the initClock() method sets up a timer:
// creates a Timer that fires an event once per second
ticker = new Timer(1000);
// designates the onTick() method to handle Timer events
ticker.addEventListener(TimerEvent.TIMER, onTick);
// starts the clock ticking
ticker.start();
First this method instantiates a Timer instance that will dispatch an event once per second (every 1000 milliseconds).
Since no second
indefinitely.
The SimpleClock.onTick() method will execute once per second when the timer event is received:
public function onTick(event:TimerEvent):void
{
// updates the clock display
face.draw();
}
repeatCount parameter is passed to the Timer() constructor, the Timer will keep repeating
8
The AnalogClockFace.draw() method simply draws the clock face and hands.
Displaying the current time
Flash Player 9 and later, Adobe AIR 1.0 and later
Most of the code in the AnalogClockFace class involves setting up the clock face’s display elements. When the
AnalogClockFace is initialized, it draws a circular outline, places a numeric text label at each hour mark, and then
creates three Shape objects, one each for the hour hand, the minute hand, and the second hand on the clock.
Once the SimpleClock application is running, it calls the AnalogClockFace.draw() method each second, as follows:
/**
* Called by the parent container when the display is being drawn.
*/
public override function draw():void
{
// stores the current date and time in an instance variable
currentTime = new Date();
showTime(currentTime);
}
This method saves the current time in a variable, so the time can’t change in the middle of drawing the clock hands.
Then it calls the
showTime() method to display the hands, as the following shows:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
/**
* Displays the given Date/Time in that good old analog clock style.
*/
public function showTime(time:Date):void
{
// gets the time values
var seconds:uint = time.getSeconds();
var minutes:uint = time.getMinutes();
var hours:uint = time.getHours();
// multiplies by 6 to get degrees
this.secondHand.rotation = 180 + (seconds * 6);
this.minuteHand.rotation = 180 + (minutes * 6);
// Multiply by 30 to get basic degrees, then
// add up to 29.5 degrees (59 * 0.5)
// to account for the minutes.
this.hourHand.rotation = 180 + (hours * 30) + (minutes * 0.5);
}
First, this method extracts the values for the hours, minutes, and seconds of the current time. Then it uses these values
to calculate the angle for each hand. Since the second hand makes a full rotation in 60 seconds, it rotates 6 degrees each
second (360/60). The minute hand rotates the same amount each minute.
9
The hour hand updates every minute, too, so it can show some progress as the minutes tick by. It rotates 30 degrees
each hour (360/12), but it also rotates half a degree each minute (30 degrees divided by 60 minutes).
Last updated 3/21/2011
Chapter 2: Working with strings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class contains methods that let you work with text strings. Strings are important in working with many
objects. The methods described here are useful for working with strings used in objects such as TextField, StaticText,
XML, ContextMenu, and FileReference objects.
Strings are sequences of characters. ActionScript 3.0 supports ASCII and Unicode characters.
More Help topics
String
RegExp
parseFloat()
parseInt()
10
Basics of strings
Flash Player 9 and later, Adobe AIR 1.0 and later
In programming parlance, a string is a text value—a sequence of letters, numbers, or other characters strung together
into a single value. For instance, this line of code creates a variable with the data type String and assigns a literal string
value to that variable:
var albumName:String = "Three for the money";
As this example shows, in ActionScript you can denote a string value by surrounding text with double or single
quotation marks. Here are several more examples of strings:
"Hello"
"555-7649"
"http://www.adobe.com/"
Any time you manipulate a piece of text in ActionScript, you are working with a string value. The ActionScript String
class is the data type you can use to work with text values. String instances are frequently used for properties, method
parameters, and so forth in many other ActionScript classes.
Important concepts and terms
The following reference list contains important terms related to strings that you will encounter:
ASCII A system for representing text characters and symbols in computer programs. The ASCII system supports the
26-letter English alphabet, plus a limited set of additional characters.
Character The smallest unit of text data (a single letter or symbol).
Concatenation Joining multiple string values together by adding one to the end of the other, creating a new string
value.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Empty string A string that contains no text, white space, or other characters, written as "". An empty string value is
different from a String variable with a null value—a null String variable is a variable that does not have a String instance
assigned to it, whereas an empty string has an instance with a value that contains no characters.
String A textual value (sequence of characters).
String literal (or “literal string”) A string value written explicitly in code, written as a text value surrounded by double
quotation marks or single quotation marks.
Substring A string that is a portion of another string.
Unicode A standard system for representing text characters and symbols in computer programs. The Unicode system
allows for the use of any character in any writing system.
Creating strings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class is used to represent string (textual) data in ActionScript 3.0. ActionScript strings support both ASCII
and Unicode characters. The simplest way to create a string is to use a string literal. To declare a string literal, use
straight double quotation mark (
equivalent:
") or single quotation mark (') characters. For example, the following two strings are
11
var str1:String = "hello";
var str2:String = 'hello';
You can also declare a string by using the new operator, as follows:
var str1:String = new String("hello");
var str2:String = new String(str1);
var str3:String = new String(); // str3 == ""
The following two strings are equivalent:
var str1:String = "hello";
var str2:String = new String("hello");
To use single quotation marks (') within a string literal defined with single quotation mark (') delimiters, use the
backslash escape character (
quotation marks (
var str1:String = "That's \"A-OK\"";
var str2:String = 'That\'s "A-OK"';
") delimiters, use the backslash escape character (\). The following two strings are equivalent:
\). Similarly, to use double quotation marks (") within a string literal defined with double
You may choose to use single quotation marks or double quotation marks based on any single or double quotation
marks that exist in a string literal, as in the following:
var str1:String = "ActionScript <span class='heavy'>3.0</span>";
var str2:String = '<item id="155">banana</item>';
Keep in mind that ActionScript distinguishes between a straight single quotation mark (') and a left or right single
quotation mark (
' or ' ). The same is true for double quotation marks. Use straight quotation marks to delineate
string literals. When pasting text from another source into ActionScript, be sure to use the correct characters.
As the following table shows, you can use the backslash escape character (\) to define other characters in string literals:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Escape sequenceCharacter
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tTab
12
\unnnnThe Unicode character with the character code specified by the hexadecimal number nnnn; for
\\xnnThe ASCII character with the character code specified by the hexadecimal number nn
\'Single quotation mark
\"Double quotation mark
\\Single backslash character
\u263a is the smiley character.
example,
The length property
Flash Player 9 and later, Adobe AIR 1.0 and later
Every string has a length property, which is equal to the number of characters in the string:
var str:String = "Adobe";
trace(str.length); // output: 5
An empty string and a null string both have a length of 0, as the following example shows:
var str1:String = new String();
trace(str1.length); // output: 0
Every character in a string has an index position in the string (an integer). The index position of the first character is
0. For example, in the following string, the character
"yellow"
You can examine individual characters in various positions in a string using the charAt() method and the
charCodeAt() method, as in this example:
var str:String = "hello world!";
for (var i:int = 0; i < str.length; i++)
{
trace(str.charAt(i), "-", str.charCodeAt(i));
}
Last updated 3/21/2011
y is in position 0 and the character w is in position 5:
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
When you run this code, the following output is produced:
h - 104
e - 101
l - 108
l - 108
o - 111
- 32
w - 119
o - 111
r - 114
l - 108
d - 100
! - 33
You can also use character codes to define a string using the fromCharCode() method, as the following example
shows:
var myStr:String = String.fromCharCode(104,101,108,108,111,32,119,111,114,108,100,33);
// Sets myStr to "hello world!"
13
Comparing strings
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the following operators to compare strings: <, <=, !=, ==, =>, and >. These operators can be used with
conditional statements, such as
var str1:String = "Apple";
var str2:String = "apple";
if (str1 < str2)
{
trace("A < a, B < b, C < c, ...");
}
When using these operators with strings, ActionScript considers the character code value of each character in the
string, comparing characters from left to right, as in the following:
Additionally, the String class includes a concat() method, which can be used as follows:
var str1:String = "Bonjour";
var str2:String = "from";
var str3:String = "Paris";
var str4:String = str1.concat(" ", str2, " ", str3);
// str4 == "Bonjour from Paris"
If you use the + operator (or the += operator) with a String object and an object that is not a string, ActionScript
automatically converts the nonstring object to a String object in order to evaluate the expression, as shown in this
example:
Substrings are sequential characters within a string. For example, the string "abc" has the following substrings: "",
"a", "ab", "abc", "b", "bc", "c". You can use ActionScript methods to locate substrings of a string.
Patterns are defined in ActionScript by strings or by regular expressions. For example, the following regular expression
defines a specific pattern—the letters A, B, and C followed by a digit character (the forward slashes are regular
expression delimiters):
/ABC\d/
ActionScript includes methods for finding patterns in strings and for replacing found matches with replacement
substrings. These methods are described in the following sections.
Regular expressions can define intricate patterns. For more information, see “Using regular expressions” on page 76.
Finding a substring by character position
Flash Player 9 and later, Adobe AIR 1.0 and later
15
The substr() and substring() methods are similar. Both return a substring of a string. Both take two parameters.
In both methods, the first parameter is the position of the starting character in the given string. However, in the
substr() method, the second parameter is the length of the substring to return, and in the substring() method, the
second parameter is the position of the character at the end of the substring (which is not included in the returned
string). This example shows the difference between these two methods:
var str:String = "Hello from Paris, Texas!!!";
trace(str.substr(11,15)); // output: Paris, Texas!!!
trace(str.substring(11,15)); // output: Pari
The slice() method functions similarly to the substring() method. When given two non-negative integers as
parameters, it works exactly the same. However, the
slice() method can take negative integers as parameters, in
which case the character position is taken from the end of the string, as shown in the following example:
var str:String = "Hello from Paris, Texas!!!";
trace(str.slice(11,15)); // output: Pari
trace(str.slice(-3,-1)); // output: !!
trace(str.slice(-3,26)); // output: !!!
trace(str.slice(-3,str.length)); // output: !!!
trace(str.slice(-8,-3)); // output: Texas
You can combine non-negative and negative integers as the parameters of the slice() method.
Finding the character position of a matching substring
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the indexOf() and lastIndexOf() methods to locate matching substrings within a string, as the
following example shows:
var str:String = "The moon, the stars, the sea, the land";
trace(str.indexOf("the")); // output: 10
Notice that the indexOf() method is case-sensitive.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
You can specify a second parameter to indicate the index position in the string from which to start the search, as
follows:
var str:String = "The moon, the stars, the sea, the land"
trace(str.indexOf("the", 11)); // output: 21
The lastIndexOf() method finds the last occurrence of a substring in the string:
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the")); // output: 30
If you include a second parameter with the lastIndexOf() method, the search is conducted from that index position
in the string working backward (from right to left):
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the", 29)); // output: 21
Creating an array of substrings segmented by a delimiter
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the split() method to create an array of substrings, which is divided based on a delimiter. For example,
you can segment a comma-delimited or tab-delimited string into multiple strings.
16
The following example shows how to split an array into substrings with the ampersand (&) character as the delimiter:
var queryStr:String = "first=joe&last=cheng&title=manager&StartDate=3/6/65";
var params:Array = queryStr.split("&", 2); // params == ["first=joe","last=cheng"]
The second parameter of the split() method, which is optional, defines the maximum size of the array that is
returned.
You can also use a regular expression as the delimiter character:
var str:String = "Give me\t5."
var a:Array = str.split(/\s+/); // a == ["Give","me","5."]
For more information, see “Using regular expressions” on page 76 and the ActionScript 3.0 Reference for the Adobe
Flash Platform.
Finding patterns in strings and replacing substrings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class includes the following methods for working with patterns in strings:
• Use the match() and search() methods to locate substrings that match a pattern.
• Use the replace() method to find substrings that match a pattern and replace them with a specified substring.
These methods are described in the following sections.
You can use strings or regular expressions to define patterns used in these methods. For more information on regular
expressions, see
“Using regular expressions” on page 76.
Finding matching substrings
The search() method returns the index position of the first substring that matches a given pattern, as shown in this
example:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
var str:String = "The more the merrier.";
// (This search is case-sensitive.)
trace(str.search("the")); // output: 9
You can also use regular expressions to define the pattern to match, as this example shows:
var pattern:RegExp = /the/i;
var str:String = "The more the merrier.";
trace(str.search(pattern)); // 0
The output of the trace() method is 0, because the first character in the string is index position 0. The i flag is set in
the regular expression, so the search is not case-sensitive.
The search() method finds only one match and returns its starting index position, even if the g (global) flag is set in
the regular expression.
The following example shows a more intricate regular expression, one that matches a string in double quotation marks:
var pattern:RegExp = /"[^"]*"/;
var str:String = "The \"more\" the merrier.";
trace(str.search(pattern)); // output: 4
str = "The \"more the merrier.";
trace(str.search(pattern)); // output: -1
// (Indicates no match, since there is no closing double quotation mark.)
17
The match() method works similarly. It searches for a matching substring. However, when you use the global flag in
a regular expression pattern, as in the following example,
var str:String = "bob@example.com, omar@example.org";
var pattern:RegExp = /\w*@\w*\.[org|com]+/g;
var results:Array = str.match(pattern);
match() returns an array of matching substrings:
The results array is set to the following:
["bob@example.com","omar@example.org"]
For more information on regular expressions, see “Using regular expressions” on page 76.
Replacing matched substrings
You can use the replace() method to search for a specified pattern in a string and replace matches with the specified
replacement string, as the following example shows:
var str:String = "She sells seashells by the seashore.";
var pattern:RegExp = /sh/gi;
trace(str.replace(pattern, "sch")); //sche sells seaschells by the seaschore.
Note that in this example, the matched strings are not case-sensitive because the i (ignoreCase) flag is set in the
regular expression, and multiple matches are replaced because the
g (global) flag is set. For more information, see
“Using regular expressions” on page 76.
You can include the following $ replacement codes in the replacement string. The replacement text shown in the
following table is inserted in place of the
$ replacement code:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
$ CodeReplacement Text
$$$
$&The matched substring.
18
$`The portion of the string that precedes the matched substring. This code uses the straight left single quotation
mark character (
$'The portion of the string that follows the matched substring. This code uses the straight single quotation mark (' ).
$nThe nth captured parenthetical group match, where n is a single digit, 1-9, and $n is not followed by a decimal digit.
$nnThe nnth captured parenthetical group match, where nn is a two-digit decimal number, 01–99. If the nnth capture
is undefined, the replacement text is an empty string.
`), not the straight single quotation mark (') or the left curly single quotation mark (' ).
For example, the following shows the use of the $2 and $1 replacement codes, which represent the first and second
capturing group matched:
var str:String = "flip-flop";
var pattern:RegExp = /(\w+)-(\w+)/g;
trace(str.replace(pattern, "$2-$1")); // flop-flip
You can also use a function as the second parameter of the replace() method. The matching text is replaced by the
returned value of the function.
var str:String = "Now only $9.95!";
var price:RegExp = /\$([\d,]+.\d+)+/i;
trace(str.replace(price, usdToEuro));
function usdToEuro(matchedSubstring:String, capturedMatch1:String, index:int,
str:String):String
{
var usd:String = capturedMatch1;
usd = usd.replace(",", "");
var exchangeRate:Number = 0.853690;
var euro:Number = parseFloat(usd) * exchangeRate;
const euroSymbol:String = String.fromCharCode(8364);
return euro.toFixed(2) + " " + euroSymbol;
}
When you use a function as the second parameter of the replace() method, the following arguments are passed to
the function:
• The matching portion of the string.
• Any capturing parenthetical group matches. The number of arguments passed this way will vary depending on the
number of parenthetical matches. You can determine the number of parenthetical matches by checking
arguments.length - 3 within the function code.
• The index position in the string where the match begins.
• The complete string.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Converting strings between uppercase and lowercase
Flash Player 9 and later, Adobe AIR 1.0 and later
As the following example shows, the toLowerCase() method and the toUpperCase() method convert alphabetical
characters in the string to lowercase and uppercase, respectively:
var str:String = "Dr. Bob Roberts, #9."
trace(str.toLowerCase()); // dr. bob roberts, #9.
trace(str.toUpperCase()); // DR. BOB ROBERTS, #9.
After these methods are executed, the source string remains unchanged. To transform the source string, use the
following code:
str = str.toUpperCase();
These methods work with extended characters, not simply a–z and A–Z:
var str:String = "José Barça";
trace(str.toUpperCase(), str.toLowerCase()); // JOSÉ BARÇA josé barça
19
Strings example: ASCII art
Flash Player 9 and later, Adobe AIR 1.0 and later
This ASCII Art example shows a number of features of working with the String class in ActionScript 3.0, including the
following:
• The split() method of the String class is used to extract values from a character-delimited string (image
information in a tab-delimited text file).
• Several string-manipulation techniques, including split(), concatenation, and extracting a portion of the string
substring() and substr(), are used to capitalize the first letter of each word in the image titles.
using
• The getCharAt() method is used to get a single character from a string (to determine the ASCII character
corresponding to a grayscale bitmap value).
• String concatenation is used to build up the ASCII art representation of an image one character at a time.
The term ASCII art refers to a text representations of an image, in which a grid of monospaced font characters, such
as Courier New characters, plots the image. The following image shows an example of ASCII art produced by the
application:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
The ASCII art version of the graphic is shown on the right.
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The
ASCIIArt application files can be found in the folder Samples/AsciiArt. The application consists of the following files:
FileDescription
20
AsciiArtApp.mxml
or
AsciiArtApp.fla
com/example/programmingas3/asciiArt/AsciiArtBuilder.asThe class that provides the main functionality of the
com/example/programmingas3/asciiArt/BitmapToAsciiConverter.asA class that provides the parseBitmapData() method for
com/example/programmingas3/asciiArt/Image.asA class which represents a loaded bitmap image.
com/example/programmingas3/asciiArt/ImageInfo.asA class representing metadata for an ASCII art image (such as
image/A folder containing images used by the application.
txt/ImageData.txtA tab-delimited text file, containing information on the
The main application file in Flash (FLA) or Flex (MXML)
application, including extracting image metadata from a text
file, loading the images, and managing the image-to-text
conversion process.
converting image data into a String version.
title, image file URL, and so on).
images to be loaded by the application.
Extracting tab-delimited values
Flash Player 9 and later, Adobe AIR 1.0 and later
This example uses the common practice of storing application data separate from the application itself; that way, if the
data changes (for example, if another image is added or an image’s title changes), there is no need to recreate the SWF
file. In this case, the image metadata, including the image title, the URL of the actual image file, and some values that
are used to manipulate the image, are stored in a text file (the txt/ImageData.txt file in the project). The contents of the
text file are as follows:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
FILENAMETITLEWHITE_THRESHHOLDBLACK_THRESHHOLD
FruitBasket.jpgPear, apple, orange, and bananad810
Banana.jpgA picture of a bananaC820
Orange.jpgorangeFF20
Apple.jpgpicture of an apple6E10
The file uses a specific tab-delimited format. The first line (row) is a heading row. The remaining lines contain the
following data for each bitmap to be loaded:
• The filename of the bitmap.
• The display name of the bitmap.
• The white-threshold and black-threshold values for the bitmaps. These are hex values above which and below
which a pixel is to be considered completely white or completely black.
As soon as the application starts, the AsciiArtBuilder class loads and parses the contents of the text file in order to
create the “stack” of images that it will display, using the following code from the AsciiArtBuilder class’s
parseImageInfo() method:
var lines:Array = _imageInfoLoader.data.split("\n");
var numLines:uint = lines.length;
for (var i:uint = 1; i < numLines; i++)
{
var imageInfoRaw:String = lines[i];
...
if (imageInfoRaw.length > 0)
{
// Create a new image info record and add it to the array of image info.
var imageInfo:ImageInfo = new ImageInfo();
// Split the current line into values (separated by tab (\t)
// characters) and extract the individual properties:
var imageProperties:Array = imageInfoRaw.split("\t");
imageInfo.fileName = imageProperties[0];
imageInfo.title = normalizeTitle(imageProperties[1]);
imageInfo.whiteThreshold = parseInt(imageProperties[2], 16);
imageInfo.blackThreshold = parseInt(imageProperties[3], 16);
result.push(imageInfo);
}
}
21
The entire contents of the text file are contained in a single String instance, the _imageInfoLoader.data property.
Using the
Array (
the lines (except the first, because it contains only headers rather than actual content). Inside the loop, the
split() method with the newline character ("\n") as a parameter, the String instance is divided into an
lines) whose elements are the individual lines of the text file. Next, the code uses a loop to work with each of
split()
method is used once again to divide the contents of the single line into a set of values (the Array object named
imageProperties). The parameter used with the split() method in this case is the tab ("\t") character, because the
values in each line are delineated by tab characters.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Using String methods to normalize image titles
Flash Player 9 and later, Adobe AIR 1.0 and later
One of the design decisions for this application is that all the image titles are displayed using a standard format, with
the first letter of each word capitalized (except for a few words that are commonly not capitalized in English titles).
Rather than assume that the text file contains properly formatted titles, the application formats the titles while they’re
being extracted from the text file.
In the previous code listing, as part of extracting individual image metadata values, the following line of code is used:
In that code, the image’s title from the text file is passed through the normalizeTitle() method before it is stored in
the ImageInfo object:
private function normalizeTitle(title:String):String
{
var words:Array = title.split(" ");
var len:uint = words.length;
for (var i:uint; i < len; i++)
{
words[i] = capitalizeFirstLetter(words[i]);
}
return words.join(" ");
}
22
This method uses the split() method to divide the title into individual words (separated by the space character),
passes each word through the
capitalizeFirstLetter() method, and then uses the Array class’s join() method
to combine the words back into a single string again.
As its name suggests, the capitalizeFirstLetter() method actually does the work of capitalizing the first letter of
each word:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
/**
* Capitalizes the first letter of a single word, unless it's one of
* a set of words that are normally not capitalized in English.
*/
private function capitalizeFirstLetter(word:String):String
{
switch (word)
{
case "and":
case "the":
case "in":
case "an":
case "or":
case "at":
case "of":
case "a":
// Don't do anything to these words.
break;
default:
// For any other word, capitalize the first character.
var firstLetter:String = word.substr(0, 1);
firstLetter = firstLetter.toUpperCase();
var otherLetters:String = word.substring(1);
word = firstLetter + otherLetters;
}
return word;
}
23
In English, the initial character of each word in a title is not capitalized if it is one of the following words: “and,” “the,”
“in,” “an,” “or,” “at,” “of,” or “a.” (This is a simplified version of the rules.) To execute this logic, the code first uses a
switch statement to check if the word is one of the words that should not be capitalized. If so, the code simply jumps
out of the
switch statement. On the other hand, if the word should be capitalized, that is done in several steps, as
follows:
1 The first letter of the word is extracted using substr(0, 1), which extracts a substring starting with the character
at index 0 (the first letter in the string, as indicated by the first parameter
length (indicated by the second parameter
1).
0). The substring will be one character in
2 That character is capitalized using the toUpperCase() method.
3 The remaining characters of the original word are extracted using substring(1), which extracts a substring
starting at index 1 (the second letter) through the end of the string (indicated by leaving off the second parameter
substring() method).
of the
4 The final word is created by combining the newly capitalized first letter with the remaining letters using string
concatenation:
firstLetter + otherLetters.
Generating the ASCII art text
Flash Player 9 and later, Adobe AIR 1.0 and later
The BitmapToAsciiConverter class provides the functionality of converting a bitmap image to its ASCII text
representation. This process is performed by the
parseBitmapData() method, which is partially shown here:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
var result:String = "";
// Loop through the rows of pixels top to bottom:
for (var y:uint = 0; y < _data.height; y += verticalResolution)
{
// Within each row, loop through pixels left to right:
for (var x:uint = 0; x < _data.width; x += horizontalResolution)
{
...
// Convert the gray value in the 0-255 range to a value
// in the 0-64 range (since that's the number of "shades of
// gray" in the set of available characters):
index = Math.floor(grayVal / 4);
result += palette.charAt(index);
}
result += "\n";
}
return result;
This code first defines a String instance named result that will be used to build up the ASCII art version of the bitmap
image. Next, it loops through individual pixels of the source bitmap image. Using several color-manipulation
techniques (omitted here for brevity), it converts the red, green, and blue color values of an individual pixel to a single
grayscale value (a number from 0 to 255). The code then divides that value by 4 (as shown) to convert it to a value in
the 0-63 scale, which is stored in the variable
index. (The 0-63 scale is used because the “palette” of available ASCII
characters used by this application contains 64 values.) The palette of characters is defined as a String instance in the
BitmapToAsciiConverter class:
24
// The characters are in order from darkest to lightest, so that their
// position (index) in the string corresponds to a relative color value
// (0 = black).
private static const palette:String =
"@#$%&8BMW*mwqpdbkhaoQ0OZXYUJCLtfjzxnuvcr[]{}1()|/?Il!i><+_~-;,. ";
Since the index variable defines which ASCII character in the palette corresponds to the current pixel in the bitmap
image, that character is retrieved from the
result String instance using the concatenation assignment operator (+=). In addition, at the end of each row of pixels,
a newline character is concatenated to the end of the
palette String using the charAt() method. It is then appended to the
result String, forcing the line to wrap to create a new row of
character “pixels.”
Last updated 3/21/2011
Chapter 3: Working with arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
Arrays allow you to store multiple values in a single data structure. You can use simple indexed arrays that store values
using fixed ordinal integer indexes or complex associative arrays that store values using arbitrary keys. Arrays can also
be multidimensional, containing elements that are themselves arrays. Finally, you can use a Vector for an array whose
elements are all instances of the same data type.
More Help topics
Array
Vector
Basics of arrays
25
Flash Player 9 and later, Adobe AIR 1.0 and later
Often in programming you’ll need to work with a set of items rather than a single object. For example, in a music player
application, you might want to have a list of songs waiting to be played. You wouldn’t want to have to create a separate
variable for each song on that list. It would be preferable to have all the Song objects together in a bundle, and be able
to work with them as a group.
An array is a programming element that acts as a container for a set of items, such as a list of songs. Most commonly
all the items in an array are instances of the same class, but that is not a requirement in ActionScript. The individual
items in an array are known as the array’s elements. You can think of an array as a file drawer for variables. Variables
can be added as elements in the array, which is like placing a folder into the file drawer. You can work with the array
as a single variable (like carrying the whole drawer to a different location). You can work with the variables as a group
(like flipping through the folders one by one searching for a piece of information). You can also access them
individually (like opening the drawer and selecting a single folder).
For example, imagine you’re creating a music player application where a user can select multiple songs and add them
to a playlist. In your ActionScript code, you have a method named
array as a parameter. No matter how many songs you want to add to the list (a few, a lot, or even only one), you call
addSongsToPlaylist() method only one time, passing it the array containing the Song objects. Inside the
the
addSongsToPlaylist() method, you can use a loop to go through the array’s elements (the songs) one by one and
actually add them to the playlist.
The most common type of ActionScript array is an indexed array. In an indexed array each item is stored in a
numbered slot (known as an index). Items are accessed using the number, like an address. Indexed arrays work well
for most programming needs. The Array class is one common class that’s used to represent an indexed array.
addSongsToPlaylist(), which accepts a single
Often, an indexed array is used to store multiple items of the same type (objects that are instances of the same class).
The Array class doesn’t have any means for restricting the type of items it contains. The Vector class is a type of indexed
array in which all the items in a single array are the same type. Using a Vector instance instead of an Array instance
can also provide performance improvements and other benefits. The Vector class is available starting with Flash Player
10 and Adobe AIR 1.5.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
A special use of an indexed array is a multidimensional array. A multidimensional array is an indexed array whose
elements are indexed arrays (which in turn contain other elements).
Another type of array is an associative array, which uses a string key instead of a numeric index to identify individual
elements. Finally, ActionScript 3.0 also includes the Dictionary class, which represents a dictionary. A dictionary is an
array that allows you to use any type of object as a key to distinguish between elements.
Important concepts and terms
The following reference list contains important terms that you will encounter when programming array and vector
handling routines:
Array An object that serves as a container to group multiple objects.
Array access ([]) operator A pair of square brackets surrounding an index or key that uniquely identifies an array
element. This syntax is used after an array variable name to specify a single element of the array rather than the entire
array.
Associative array An array that uses string keys to identify individual elements.
Base type The data type of the objects that a Vector instance is allowed to store.
Dictionary An array whose items consist of pairs of objects, known as the key and the value. The key is used instead
of a numeric index to identify a single element.
26
Element A single item in an array.
Index The numeric “address” used to identify a single element in an indexed array.
Indexed array The standard type of array that stores each element in a numbered position, and uses the number
(index) to identify individual elements.
Key The string or object used to identify a single element in an associative array or a dictionary.
Multidimensional array An array containing items that are arrays rather than single values.
T The standard convention that’s used in this documentation to represent the base type of a Vector instance, whatever
that base type happens to be. The T convention is used to represent a class name, as shown in the Type parameter
description. (“T” stands for “type,” as in “data type.”).
Type parameter The syntax that’s used with the Vector class name to specify the Vector’s base type (the data type of
the objects that it stores). The syntax consists of a period (
<>). Put together, it looks like this: Vector.<T>. In this documentation, the class specified in the type parameter is
(
represented generically as
Vector A type of array whose elements are all instances of the same data type.
T.
.), then the data type name surrounded by angle brackets
Indexed arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
Indexed arrays store a series of one or more values organized such that each value can be accessed using an unsigned
integer value. The first index is always the number 0, and the index increments by 1 for each subsequent element added
to the array. In ActionScript 3.0, two classes are used as indexed arrays: the Array class and the Vector class.
Indexed arrays use an unsigned 32-bit integer for the index number. The maximum size of an indexed array is 232 - 1
or 4,294,967,295. An attempt to create an array that is larger than the maximum size results in a run-time error.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
To access an individual element of an indexed array, you use the array access ([]) operator to specify the index position
of the element you wish to access. For example, the following code represents the first element (the element at index
0) in an indexed array named
songTitles[0]
songTitles:
The combination of the array variable name followed by the index in square brackets functions as a single identifier.
(In other words, it can be used in any way a variable name can). You can assign a value to an indexed array element by
using the name and index on the left side of an assignment statement:
songTitles[1] = "Symphony No. 5 in D minor";
Likewise, you can retrieve the value of an indexed array element by using the name and index on the right side of an
assignment statement:
var nextSong:String = songTitles[2];
You can also use a variable in the square brackets rather than providing an explicit value. (The variable must contain
a non-negative integer value such as a uint, a positive int, or a positive integer Number instance). This technique is
commonly used to “loop over” the elements in an indexed array and perform an operation on some or all the elements.
The following code listing demonstrates this technique. The code uses a loop to access each value in an Array object
oddNumbers. It uses the trace() statement to print each value in the form “oddNumber[index] = value”:
named
var oddNumbers:Array = [1, 3, 5, 7, 9, 11];
var len:uint = oddNumbers.length;
for (var i:uint = 0; i < len; i++)
{
The first type of indexed array is the Array class. An Array instance can hold a value of any data type. The same Array
object can hold objects that are of different data types. For example, a single Array instance can have a String value in
index 0, a Number instance in index 1, and an XML object in index 2.
The Vector class
Another type of indexed array that’s available in ActionScript 3.0 is the Vector class. A Vector instance is a typed array,
which means that all the elements in a Vector instance always have the same data type.
Note: The Vector class is available starting with Flash Player 10 and Adobe AIR 1.5.
When you declare a Vector variable or instantiate a Vector object, you explicitly specify the data type of the objects
that the Vector can contain. The specified data type is known as the Vector’s base type. At run time and at compile time
(in strict mode), any code that sets the value of a Vector element or retrieves a value from a Vector is checked. If the
data type of the object being added or retrieved doesn’t match the Vector’s base type, an error occurs.
In addition to the data type restriction, the Vector class has other restrictions that distinguish it from the Array class:
• A Vector is a dense array. An Array object may have values in indices 0 and 7 even if it has no values in positions 1
through 6. However, a Vector must have a value (or
null) in each index.
• A Vector can optionally be fixed-length. This means that the number of elements the Vector contains can’t change.
• Access to a Vector’s elements is bounds-checked. You can never read a value from an index greater than the final
element (
other words, you can only set a value at an existing index or at index
length - 1). You can never set a value with an index more than one beyond the current final index. (In
[length].)
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
As a result of its restrictions, a Vector has three primary benefits over an Array instance whose elements are all
instances of a single class:
• Performance: array element access and iteration are much faster when using a Vector instance than when using an
Array instance.
• Type safety: in strict mode the compiler can identify data type errors. Examples of such errors include assigning a
value of the incorrect data type to a Vector or expecting the wrong data type when reading a value from a Vector.
At run time, data types are also checked when adding data to or reading data from a Vector object. Note, however,
that when you use the
push() method or unshift() method to add values to a Vector, the arguments’ data types
are not checked at compile time. When using those methods the values are still checked at run time.
• Reliability: runtime range checking (or fixed-length checking) increases reliability significantly over Arrays.
Aside from the additional restrictions and benefits, the Vector class is very much like the Array class. The properties
and methods of a Vector object are similar—for the most part identical—to the properties and methods of an Array.
In most situations where you would use an Array in which all the elements have the same data type, a Vector instance
is preferable.
Creating arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
28
You can use several techniques to create an Array instance or a Vector instance. However, the techniques to create each
type of array are somewhat different.
Creating an Array instance
Flash Player 9 and later, Adobe AIR 1.0 and later
You create an Array object by calling the Array() constructor or by using Array literal syntax.
The Array() constructor function can be used in three ways. First, if you call the constructor with no arguments, you
get an empty array. You can use the
example, the following code calls the
var names:Array = new Array();
trace(names.length); // output: 0
Second, if you use a number as the only parameter to the Array() constructor, an array of that length is created, with
each element’s value set to
undefined. The argument must be an unsigned integer between the values 0 and
4,294,967,295. For example, the following code calls the
Third, if you call the constructor and pass a list of elements as parameters, an array is created, with elements
corresponding to each of the parameters. The following code passes three arguments to the
length property of the Array class to verify that the array has no elements. For
Array() constructor with no arguments:
Array() constructor with a single numeric argument:
Array() constructor:
var names:Array = new Array("John", "Jane", "David");
trace(names.length); // output: 3
trace(names[0]); // output: John
trace(names[1]); // output: Jane
trace(names[2]); // output: David
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
You can also create arrays with Array literals. An Array literal can be assigned directly to an array variable, as shown
in the following example:
var names:Array = ["John", "Jane", "David"];
Creating a Vector instance
Flash Player 10 and later, Adobe AIR 1.5 and later
You create a Vector instance by calling the Vector.<T>() constructor. You can also create a Vector by calling the
Vector.<T>() global function. That function converts a specified object to a Vector instance. In Flash
Professional
Vector literal syntax.
Any time you declare a Vector variable (or similarly, a Vector method parameter or method return type) you specify
the base type of the Vector variable. You also specify the base type when you create a Vector instance by calling the
Vector.<T>() constructor. Put another way, any time you use the term Vector in ActionScript, it is accompanied by
a base type.
You specify the Vector’s base type using type parameter syntax. The type parameter immediately follows the word
Vector in the code. It consists of a dot (.), then the base class name surrounded by angle brackets (<>), as shown in
this example:
CS5 and later, Flash Builder 4 and later, and Flex 4 and later, you can also create a vector instance by using
29
var v:Vector.<String>;
v = new Vector.<String>();
In the first line of the example, the variable v is declared as a Vector.<String> instance. In other words, it represents
an indexed array that can only hold String instances. The second line calls the
instance of the same Vector type (that is, a Vector whose elements are all String objects). It assigns that object to
Vector() constructor to create an
v.
Using the Vector.<T>() constructor
If you use the Vector.<T>() constructor without any arguments, it creates an empty Vector instance. You can test
that a Vector is empty by checking its
length property. For example, the following code calls the Vector.<T>()
constructor with no arguments:
var names:Vector.<String> = new Vector.<String>();
trace(names.length); // output: 0
If you know ahead of time how many elements a Vector initially needs, you can pre-define the number of elements in
the Vector. To create a Vector with a certain number of elements, pass the number of elements as the first parameter
length parameter). Because Vector elements can’t be empty, the elements are filled with instances of the base
(the
type. If the base type is a reference type that allows
all contain the default value for the class. For example, a uint variable can’t be
code listing the Vector named
var ages:Vector.<uint> = new Vector.<uint>(7);
trace(ages); // output: 0,0,0,0,0,0,0
ages is created with seven elements, each containing the value 0:
null values, the elements all contain null. Otherwise, the elements
null. Consequently, in the following
Finally, using the Vector.<T>() constructor you can also create a fixed-length Vector by passing true for the second
parameter (the
fixed parameter). In that case the Vector is created with the specified number of elements and the
number of elements can’t be changed. Note, however, that you can still change the values of the elements of a fixedlength Vector.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Using the Vector literal syntax constructor
In Flash Professional CS5 and later, Flash Builder 4 and later, and Flex 4 and later, you can pass a list of values to the
Vector.<T>() constructor to specify the Vector’s initial values:
// var v:Vector.<T> = new <T>[E0, ..., En-1 ,];
// For example:
var v:Vector.<int> = new <int>[0,1,2,];
The following information applies to this syntax:
• The trailing comma is optional.
• Empty items in the array are not supported; a statement such as var v:Vector.<int> = new <int>[0,,2,]
throws a compiler error.
• You can't specify a default length for the Vector instance. Instead, the length is the same as the number of elements
in the initialization list.
• You can't specify whether the Vector instance has a fixed length. Instead, use the fixed property.
• Data loss or errors can occur if items passed as values don't match the specified type. For example:
var v:Vector.<int> = new <int>[4.2]; // compiler error when running in strict mode
trace(v[0]); //returns 4 when not running in strict mode
30
Using the Vector.<T>() global function
In addition to the Vector.<T>() and Vector literal syntax constructors, you can also use the Vector.<T>() global
function to create a Vector object. The
Vector.<T>() global function you specify the base type of the Vector that the method returns. You pass a single
Vector.<T>() global function is a conversion function. When you call the
indexed array (Array or Vector instance) as an argument. The method then returns a Vector with the specified base
type, containing the values in the source array argument. The following code listing shows the syntax for calling the
Vector.<T>() global function:
var friends:Vector.<String> = Vector.<String>(["Bob", "Larry", "Sarah"]);
The Vector.<T>() global function performs data type conversion on two levels. First, when an Array instance is
passed to the function, a Vector instance is returned. Second, whether the source array is an Array or Vector instance
the function attempts to convert the source array’s elements to values of the base type. The conversion uses standard
ActionScript data type conversion rules. For example, the following code listing converts the String values in the source
Array to integers in the result Vector. The decimal portion of the first value (
third value (
var numbers:Vector.<int> = Vector.<int>(["1.5", "17", "Waffles"]);
trace(numbers); // output: 1,17,0
"Waffles") is converted to 0 in the result:
"1.5") is truncated, and the non-numeric
If any of the source elements can’t be converted, an error occurs.
When code calls the Vector.<T>() global function, if an element in the source array is an instance of a subclass of the
specified base type, the element is added to the result Vector (no error occurs). Using the
function is the only way to convert a Vector with base type
T to a Vector with a base type that’s a superclass of T.
Vector.<T>() global
Inserting array elements
Flash Player 9 and later, Adobe AIR 1.0 and later
The most basic way to add an element to an indexed array is to use the array access ([]) operator. To set the value of
an indexed array element, use the Array or Vector object name and index number on the left side of an assignment
statement:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
songTitles[5] = "Happy Birthday";
If the Array or Vector doesn’t already have an element at that index, the index is created and the value is stored there.
If a value exists at that index, the new value replaces the existing one.
An Array object allows you to create an element at any index. However, with a Vector object you can only assign a
value to an existing index or to the next available index. The next available index corresponds to the Vector object’s
length property. The safest way to add a new element to a Vector object is to use code like this listing:
myVector[myVector.length] = valueToAdd;
Three of the Array and Vector class methods—push(), unshift(), and splice()—allow you to insert elements into
an indexed array. The
element inserted into the array using the
inserts one or more elements at the beginning of an array, which is always at index number 0. The
push() method appends one or more elements to the end of an array. In other words, the last
push() method will have the highest index number. The unshift() method
splice() method
will insert any number of items at a specified index in the array.
The following example demonstrates all three methods. An array named planets is created to store the names of the
planets in order of proximity to the Sun. First, the
unshift() method is called to insert the item that belongs at the front of the array, Mercury. Finally, the splice()
method is called to insert the items
splice(), the integer 1, directs the insertion to begin at index 1. The second argument sent to splice(), the integer
Venus and Earth after Mercury, but before Mars. The first argument sent to
0, indicates that no items should be deleted. Finally, the third and fourth arguments sent to
Earth, are the items to be inserted.
push() method is called to add the initial item, Mars. Second, the
splice(), Venus and
31
var planets:Array = new Array();
planets.push("Mars"); // array contents: Mars
planets.unshift("Mercury"); // array contents: Mercury,Mars
planets.splice(1, 0, "Venus", "Earth");
trace(planets); // array contents: Mercury,Venus,Earth,Mars
The push() and unshift() methods both return an unsigned integer that represents the length of the modified array.
splice() method returns an empty array when used to insert elements, which may seem strange, but makes more
The
sense in light of the
an array, but also to remove elements from an array. When used to remove elements, the
splice() method’s versatility. You can use the splice() method not only to insert elements into
splice() method returns
an array containing the elements removed.
Note: If a Vector object’s fixed property is true, the total number of elements in the Vector can’t change. If you try to
add a new element to a fixed-length Vector using the techniques described here, an error occurs.
Retrieving values and removing array elements
Flash Player 9 and later, Adobe AIR 1.0 and later
The simplest way to retrieve the value of an element from an indexed array is to use the array access ([]) operator. To
retrieve the value of an indexed array element, use the Array or Vector object name and index number on the right
side of an assignment statement:
var myFavoriteSong:String = songTitles[3];
It’s possible to attempt to retrieve a value from an Array or Vector using an index where no element exists. In that case,
an Array object returns the value undefined and a Vector throws a RangeError exception.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Three methods of the Array and Vector classes—pop(), shift(), and splice()—allow you to remove elements. The
pop() method removes an element from the end of the array. In other words, it removes the element at the highest
index number. The
removes the element at index number 0. The
shift() method removes an element from the beginning of the array, which means that it always
splice() method, which can also be used to insert elements, removes
an arbitrary number of elements starting at the index number specified by the first argument sent to the method.
The following example uses all three methods to remove elements from an Array instance. An Array named oceans
is created to store the names of large bodies of water. Some of the names in the Array are lakes rather than oceans, so
they need to be removed.
First, the splice() method is used to remove the items Aral and Superior, and insert the items Atlantic and
Indian. The first argument sent to splice(), the integer 2, indicates that the operation should start with the third
item in the list, which is at index 2. The second argument, 2, indicates that two items should be removed. The
remaining arguments,
Atlantic and Indian, are values to be inserted at index 2.
Second, the pop() method is used to remove last element in the array, Huron. And third, the shift() method is used
to remove the first item in the array,
var oceans:Array = ["Victoria", "Pacific", "Aral", "Superior", "Indian", "Huron"];
oceans.splice(2, 2, "Arctic", "Atlantic"); // replaces Aral and Superior
oceans.pop(); // removes Huron
oceans.shift(); // removes Victoria
trace(oceans);// output: Pacific,Arctic,Atlantic,Indian
Victoria.
32
The pop() and shift() methods both return the item that was removed. For an Array instance, the data type of the
return value is Object because arrays can hold values of any data type. For a Vector instance, the data type of the return
value is the base type of the Vector. The
You can change the
oceans Array example so that the call to splice() assigns the returned Array to a new Array
splice() method returns an Array or Vector containing the values removed.
You may come across code that uses the delete operator on an Array object element. The delete operator sets the
value of an Array element to
following code uses the
undefined, but it does not remove the element from the Array. For example, the
delete operator on the third element in the oceans Array, but the length of the Array remains
You can truncate an Array or Vector using an array’s length property. If you set the length property of an indexed
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
all valid entries were at the beginning of the array, you could use the
length minus 1. For example, if the oceans array were sorted such that
Note: If a Vector object’s fixed property is true, the total number of elements in the Vector can’t change. If you try to
remove an element from or truncate a fixed-length Vector using the techniques described here, an error occurs.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Sorting an array
Flash Player 9 and later, Adobe AIR 1.0 and later
There are three methods—reverse(), sort(), and sortOn()—that allow you to change the order of an indexed
array, either by sorting or reversing the order. All of these methods modify the existing array. The following table
summarizes these methods and their behavior for Array and Vector objects:
MethodArray behaviorVector behavior
33
reverse()Changes the order of the elements so that the last element becomes the
first element, the penultimate element becomes the second, and so on
sort()Allows you to sort the Array’s elements in a variety of predefined ways,
such as alphabetical or numeric order. You can also specify a custom
sorting algorithm.
sortOn()Allows you to sort objects that have one or more common properties,
specifying the property or properties to use as the sort keys
Identical to Array behavior
Sorts the elements according to the custom
sorting algorithm that you specify
Not available in the Vector class
The reverse() method
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
Basic sorting with the sort() method (Array class only)
For an Array instance, 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).
You may find that you need to sort your Array without regard to case, or in descending order, or perhaps your array
contains numbers that you want to sort numerically instead of alphabetically. The Array class’s
options parameter that allows you to alter each characteristic of the default sort order. The options are defined by a
sort() method has an
set of static constants in the Array class, as shown in the following list:
• Array.CASEINSENSITIVE: This option makes the sort disregard case. For example, the lowercase letter b precedes
the uppercase letter D.
• Array.DESCENDING: This reverses the default ascending sort. For example, the letter B precedes the letter A.
• Array.UNIQUESORT: This causes the sort to abort if two identical values are found.
• Array.NUMERIC: This causes numerical sorting, so that 3 precedes 10.
The following example highlights some of these options. An Array named poets is created that is sorted using several
different options.
poets.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options
trace(poets); // output: Dante,cummings,Blake,Angelou
Custom sorting with the sort() method (Array and Vector classes)
In addition to the basic sorting that’s available for an Array object, you can also define a custom sorting rule. This
technique is the only form of the
write a custom sort function and pass it as an argument to the
sort() method that is available for the Vector class. To define a custom sort, you
sort() method.
For example, if you have a list of names in which each list element contains a person’s full name, but you want to sort
the list by last name, you must use a custom sort function to parse each element and use the last name in the sort
function. The following code shows how this can be done with a custom function that is used as a parameter to the
Array.sort() method:
34
var names:Array = new Array("John Q. Smith", "Jane Doe", "Mike Jones");
function orderLastName(a, b):int
{
var lastName:RegExp = /\b\S+$/;
var name1 = a.match(lastName);
var name2 = b.match(lastName);
if (name1 < name2)
{
return -1;
}
else if (name1 > name2)
{
return 1;
}
else
{
return 0;
}
}
trace(names); // output: John Q. Smith,Jane Doe,Mike Jones
names.sort(orderLastName);
trace(names); // output: Jane Doe,Mike Jones,John Q. Smith
The custom sort function orderLastName() uses a regular expression to extract the last name from each element to
use for the comparison operation. The function identifier
sort() method on the names array. The sort function accepts two parameters, a and b, because it works on two
the
orderLastName is used as the sole parameter when calling
array elements at a time. The sort function’s return value indicates how the elements should be sorted:
• A return value of -1 indicates that the first parameter, a, precedes the second parameter, b.
• A return value of 1 indicates that the second parameter, b, precedes the first, a.
• A return value of 0 indicates that the elements have equal sorting precedence.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
The sortOn() method (Array class only)
The sortOn() method is designed for Array objects with elements that contain objects. These objects are expected to
have at least one common property that can be used as the sort key. The use of the
sortOn() method for arrays of any
other type yields unexpected results.
Note: The Vector class does not include a sortOn() method. This method is only available for Array objects.
The following example revises the poets Array so that each element is an object instead of a string. Each object holds
both the poet’s last name and year of birth.
var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});
You can use the sortOn() method to sort the Array by the born property. The sortOn() method defines two
parameters,
example,
fieldName and options. The fieldName argument must be specified as a string. In the following
sortOn() is called with two arguments, "born" and Array.NUMERIC. The Array.NUMERIC argument is used
to ensure that the sort is done numerically instead of alphabetically. This is a good practice even when all the numbers
have the same number of digits because it ensures that the sort will continue to behave as expected if a number with
fewer or more digits is later added to the array.
35
poets.sortOn("born", Array.NUMERIC);
for (var i:int = 0; i < poets.length; ++i)
{
trace(poets[i].name, poets[i].born);
}
/* output:
Wang 701
Dante 1265
Blake 1757
cummings 1894
Angelou 1928
*/
Sorting without modifying the original array (Array class only)
Generally, the sort() and sortOn() methods modify an Array. If you wish to sort an Array without modifying the
existing array, pass the
Array.RETURNINDEXEDARRAY constant as part of the options parameter. This option directs
the methods to return a new Array that reflects the sort and to leave the original Array unmodified. The Array returned
by the methods is a simple Array of index numbers that reflects the new sort order and does not contain any elements
from the original Array. For example, to sort the
Array.RETURNINDEXEDARRAY constant as part of the argument passed for the options parameter.
poets Array by birth year without modifying the Array, include the
The following example stores the returned index information in an Array named indices and uses the indices array
in conjunction with the unmodified
poets array to output the poets in order of birth year:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
var indices:Array;
indices = poets.sortOn("born", Array.NUMERIC | Array.RETURNINDEXEDARRAY);
for (var i:int = 0; i < indices.length; ++i)
{
var index:int = indices[i];
trace(poets[index].name, poets[index].born);
}
/* output:
Wang 701
Dante 1265
Blake 1757
cummings 1894
Angelou 1928
*/
Querying an array
Flash Player 9 and later, Adobe AIR 1.0 and later
Four methods of the Array and Vector classes—concat(), join(), slice(), and toString()—all query the array
for information, but do not modify the array. The
join() and toString() methods both return strings. The concat() method takes a new array or list of elements as
arguments and combines it with the existing array to create a new array. The
aptly named
startIndex and an endIndex, and returns a new array containing a copy of the elements “sliced” from
the existing array. The slice begins with the element at
That bears repeating: the element at
endIndex is not included in the return value.
concat() and slice() methods both return new arrays, while the
slice() method has two parameters,
startIndex and ends with the element just before endIndex.
36
The following example uses concat() and slice() to create new arrays using elements of other arrays:
var array1:Array = ["alpha", "beta"];
var array2:Array = array1.concat("gamma", "delta");
trace(array2); // output: alpha,beta,gamma,delta
var array3:Array = array1.concat(array2);
trace(array3); // output: alpha,beta,alpha,beta,gamma,delta
var array4:Array = array3.slice(2,5);
trace(array4); // output: alpha,beta,gamma
You can use the join() and toString() methods to query the array and return its contents as a string. If no
parameters are used for the
comma-delimited list of all elements in the array. The
parameter named
delimiter, which allows you to choose the symbol to use as a separator between each element in
join() method, the two methods behave identically—they return a string containing a
join() method, unlike the toString() method, accepts a
the returned string.
The following example creates an Array called rivers and calls both join() and toString() to return the values in
the Array as a string. The
join() method is used to return values separated by the + character.
var rivers:Array = ["Nile", "Amazon", "Yangtze", "Mississippi"];
var riverCSV:String = rivers.toString();
trace(riverCSV); // output: Nile,Amazon,Yangtze,Mississippi
var riverPSV:String = rivers.join("+");
trace(riverPSV); // output: Nile+Amazon+Yangtze+Mississippi
toString() method is used to return comma-separated values (riverCSV), while the
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
One issue to be aware of with the join() method is that any nested Array or Vector instances are always returned with
comma-separated values, no matter what separator you specify for the main array elements, as the following example
shows:
var nested:Array = ["b","c","d"];
var letters:Array = ["a",nested,"e"];
var joined:String = letters.join("+");
trace(joined); // output: a+b,c,d+e
Associative arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values.
Each key in an associative array is a unique string that is used to access a stored value. An associative array is an
instance of the Object class, which means that each key corresponds to a property name. Associative arrays are
unordered collections of key and value pairs. Your code should not expect the keys of an associative array to be in a
specific order.
ActionScript 3.0 also includes an advanced type of associative array called a dictionary. Dictionaries, which are
instances of the Dictionary class in the flash.utils package, use keys that can be of any data type. In other words,
dictionary keys are not limited to values of type String.
37
Associative arrays with string keys
Flash Player 9 and later, Adobe AIR 1.0 and later
There are two ways to create associative arrays in ActionScript 3.0. The first way is to use an Object instance. By using
an Object instance you can initialize your array with an object literal. An instance of the Object class, also called a
generic object, is functionally identical to an associative array. Each property name of the generic object serves as the
key that provides access to a stored value.
The following example creates an associative array named monitorInfo, using an object literal to initialize the array
with two key and value pairs:
var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};
trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200
If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array, as
follows:
var monitorInfo:Object = new Object();
After the array is created using either an object literal or the Object class constructor, you can add new values to the
array using either the array access (
monitorArray:
to
monitorInfo["aspect ratio"] = "16:10"; // bad form, do not use spaces
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspect ratio"], monitorInfo.colors);
// output: 16:10 16.7 million
[]) operator or the dot operator (.). The following example adds two new values
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Note that the key named aspect ratio contains a space character. This is possible with the array access ([]) operator,
but generates an error if attempted with the dot operator. Using spaces in your key names is not recommended.
The second way to create an associative array is to use the Array constructor (or the constructor of any dynamic class)
and then use either the array access (
[]) operator or the dot operator (.) to add key and value pairs to the array. If you
declare your associative array to be of type Array, you cannot use an object literal to initialize the array. The following
example creates an associative array named
a key called
var monitorInfo:Array = new Array();
monitorInfo["type"] = "Flat Panel";
monitorInfo["resolution"] = "1600 x 1200";
trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200
resolution, along with their values:
monitorInfo using the Array constructor and adds a key called type and
There is no advantage in using the Array constructor to create an associative array. You cannot use the Array.length
property or any of the methods of the Array class with associative arrays, even if you use the Array constructor or the
Array data type. The use of the Array constructor is best left for the creation of indexed arrays.
Associative arrays with object keys (Dictionaries)
Flash Player 9 and later, Adobe AIR 1.0 and later
38
You can use the Dictionary class to create an associative array that uses objects for keys rather than strings. Such arrays
are sometimes called dictionaries, hashes, or maps. For example, consider an application that determines the location
of a Sprite object based on its association with a specific container. You can use a Dictionary object to map each Sprite
object to a container.
The following code creates three instances of the Sprite class that serve as keys for the Dictionary object. Each key is
assigned a value of either
GroupB are instances of the Object class. Subsequently, you can access the value associated with each key with the array
[]) operator, as shown in the following code:
access (
GroupA or GroupB. The values can be of any data type, but in this example both GroupA and
// objects to use as keys
var spr1:Sprite = new Sprite();
var spr2:Sprite = new Sprite();
var spr3:Sprite = new Sprite();
// objects to use as values
var groupA:Object = new Object();
var groupB:Object = new Object();
// Create new key-value pairs in dictionary.
groupMap[spr1] = groupA;
groupMap[spr2] = groupB;
groupMap[spr3] = groupB;
if (groupMap[spr1] == groupA)
{
trace("spr1 is in groupA");
}
if (groupMap[spr2] == groupB)
{
trace("spr2 is in groupB");
}
if (groupMap[spr3] == groupB)
{
trace("spr3 is in groupB");
}
39
Iterating with object keys
You can iterate through the contents of a Dictionary object with either a for..in loop or a for each..in loop. A
for..in loop allows you to iterate based on the keys, whereas a for each..in loop allows you to iterate based on the
values associated with each key.
Use the for..in loop for direct access to the object keys of a Dictionary object. You can also access the values of the
Dictionary object with the array access (
dictionary to show how to iterate through a Dictionary object with the
[]) operator. The following code uses the previous example of the groupMap
for..in loop:
Use the for each..in loop for direct access to the values of a Dictionary object. The following code also uses the
groupMap dictionary to show how to iterate through a Dictionary object with the for each..in loop:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
for each (var item:Object in groupMap)
{
trace(item);
}
/* output:
[object Object]
[object Object]
[object Object]
*/
Object keys and memory management
Adobe® Flash® Player and Adobe® AIR™ use a garbage collection system to recover memory that is no longer used.
When an object has no references pointing to it, the object becomes eligible for garbage collection, and the memory is
recovered the next time the garbage collection system executes. For example, the following code creates a new object
and assigns a reference to the object to the variable
var myObject:Object = new Object();
myObject:
As long as any reference to the object exists, the garbage collection system will not recover the memory that the object
occupies. If the value of
myObject is changed such that it points to a different object or is set to the value null, the
memory occupied by the original object becomes eligible for garbage collection, but only if there are no other
references to the original object.
40
If you use myObject as a key in a Dictionary object, you are creating another reference to the original object. For
example, the following code creates two references to an object—the
myObject variable, and the key in the myMap
object:
import flash.utils.Dictionary;
var myObject:Object = new Object();
var myMap:Dictionary = new Dictionary();
myMap[myObject] = "foo";
To make the object referenced by myObject eligible for garbage collection, you must remove all references to it. In this
case, you must change the value of
myObject = null;
delete myMap[myObject];
myObject and delete the myObject key from myMap, as shown in the following code:
Alternatively, you can use the useWeakReference parameter of the Dictionary constructor to make all of the
dictionary keys weak references. The garbage collection system ignores weak references, which means that an object
that has only weak references is eligible for garbage collection. For example, in the following code, you do not need to
delete the
import flash.utils.Dictionary;
var myObject:Object = new Object();
var myMap:Dictionary = new Dictionary(true);
myMap[myObject] = "foo";
myObject = null; // Make object eligible for garbage collection.
myObject key from myMap in order to make the object eligible for garbage collection:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Multidimensional arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
Multidimensional arrays contain other arrays as elements. For example, consider a list of tasks that is stored as an
indexed array of strings:
var tasks:Array = ["wash dishes", "take out trash"];
If you want to store a separate list of tasks for each day of the week, you can create a multidimensional array with one
element for each day of the week. Each element contains an indexed array, similar to the
list of tasks. You can use any combination of indexed or associative arrays in multidimensional arrays. The examples
in the following sections use either two indexed arrays or an associative array of indexed arrays. You might want to try
the other combinations as exercises.
Two indexed arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
When you use two indexed arrays, you can visualize the result as a table or spreadsheet. The elements of the first array
represent the rows of the table, while the elements of the second array represent the columns.
tasks array, that stores the
41
For example, the following multidimensional array uses two indexed arrays to track task lists for each day of the week.
The first array,
masterTaskList, is created using the Array class constructor. Each element of the array represents a
day of the week, with index 0 representing Monday, and index 6 representing Sunday. These elements can be thought
of as the rows in the table. You can create each day’s task list by assigning an array literal to each of the seven elements
that you create in the
masterTaskList array. The array literals represent the columns in the table.
You can access individual items on any of the task lists using the array access ([]) operator. The first set of brackets
represents the day of the week, and the second set of brackets represents the task list for that day. For example, to
retrieve the second task from Wednesday’s list, first use index 2 for Wednesday, and then use index 1 for the second
task in the list.
trace(masterTaskList[2][1]); // output: dentist
To retrieve the first task from Sunday’s list, use index 6 for Sunday and index 0 for the first task on the list.
trace(masterTaskList[6][0]); // output: mow lawn
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Associative array with an indexed array
Flash Player 9 and later, Adobe AIR 1.0 and later
To make the individual arrays easier to access, you can use an associative array for the days of the week and an indexed
array for the task lists. Using an associative array allows you to use dot syntax when referring to a particular day of the
week, but at the cost of extra run-time processing to access each element of the associative array. The following
example uses an associative array as the basis of a task list, with a key and value pair for each day of the week:
You can iterate through the task list using a for..in loop, but you must use the array access ([]) operator instead of
dot syntax to access the value associated with each key. Because
are not necessarily retrieved in the order that you may expect, as the following example shows:
masterTaskList is an associative array, the elements
42
for (var day:String in masterTaskList)
{
trace(day + ": " + masterTaskList[day])
}
/* output:
Sunday: mow lawn,fix chair
Wednesday: wash dishes,dentist,wash dog
Friday: wash dishes,clean house
Thursday: wash dishes
Monday: wash dishes,take out trash
Saturday: wash dishes,wash car,pay rent
Tuesday: wash dishes,pay bills
*/
Cloning arrays
Flash Player 9 and later, Adobe AIR 1.0 and later
The Array class has no built-in method for making copies of arrays. You can create a shallowcopy of an array by calling
either the
are objects, only the references to the objects are copied rather than the objects themselves. The copy points to the same
objects as the original does. Any changes made to the objects are reflected in both arrays.
In a deep copy, any objects found in the original array are also copied so that the new array does not point to the same
objects as does the original array. Deep copying requires more than one line of code, which usually calls for the creation
of a function. Such a function could be created as a global utility function or as a method of an Array subclass.
concat() or slice() methods with no arguments. In a shallow copy, if the original array has elements that
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
The following example defines a function named clone() that does deep copying. The algorithm is borrowed from a
common Java programming technique. The function creates a deep copy by serializing the array into an instance of
the ByteArray class, and then reading the array back into a new array. This function accepts an object so that it can be
used with both indexed arrays and associative arrays, as shown in the following code:
import flash.utils.ByteArray;
function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}
Extending the Array class
Flash Player 9 and later, Adobe AIR 1.0 and later
The Array class is one of the few core classes that is not final, which means that you can create your own subclass of
Array. This section provides an example of how to create a subclass of Array and discusses some of the issues that can
arise during the process.
43
As mentioned previously, arrays in ActionScript are not typed, but you can create a subclass of Array that accepts
elements of only a specific data type. The example in the following sections defines an Array subclass named
TypedArray that limits its elements to values of the data type specified in the first parameter. The TypedArray class is
presented merely as an example of how to extend the Array class and may not be suitable for production purposes for
several reasons. First, type checking occurs at run time rather than at compile time. Second, when a TypedArray
method encounters a mismatch, the mismatch is ignored and no exception is thrown, although the methods can be
easily modified to throw exceptions. Third, the class cannot prevent the use of the array access operator to insert values
of any type into the array. Fourth, the coding style favors simplicity over performance optimization.
Note: You can use the technique described here to create a typed array. However, a better approach is to use a Vector
object. A Vector instance is a true typed array, and provides performance and other improvements over the Array class
or any subclass. The purpose of this discussion is to demonstrate how to create an Array subclass.
Declaring the subclass
Use the extends keyword to indicate that a class is a subclass of Array. A subclass of Array should use the dynamic
attribute, just as the Array class does. Otherwise, your subclass will not function properly.
The following code shows the definition of the TypedArray class, which contains a constant to hold the data type, a
constructor method, and the four methods that are capable of adding elements to the array. The code for each method
is omitted in this example, but is delineated and explained fully in the sections that follow:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
public dynamic class TypedArray extends Array
{
private const dataType:Class;
public function TypedArray(...args) {}
AS3 override function concat(...args):Array {}
AS3 override function push(...args):uint {}
AS3 override function splice(...args) {}
AS3 override function unshift(...args):uint {}
}
The four overridden methods all use the AS3 namespace instead of the public attribute because this example assumes
that the compiler option
-as3 is set to true and the compiler option -es is set to false. These are the default settings
for Adobe Flash Builder and for AdobeFlashProfessional.
If you are an advanced developer who prefers to use prototype inheritance, you can make two minor changes to the
TypedArray class to make it compile with the compiler option -es set to true. First, remove all occurrences of the
override attribute and replace the AS3 namespace with the public attribute. Second, substitute Array.prototype for
all four occurrences of
super.
44
TypedArray constructor
The subclass constructor poses an interesting challenge because the constructor must accept a list of arguments of
arbitrary length. The challenge is how to pass the arguments on to the superconstructor to create the array. If you pass
the list of arguments as an array, the superconstructor considers it a single argument of type Array and the resulting
array is always 1 element long. The traditional way to handle pass-through argument lists is to use the
Function.apply() method, which takes an array of arguments as its second parameter but converts it to a list of
arguments when executing the function. Unfortunately, the
Function.apply() method cannot be used with
constructors.
The only option left is to recreate the logic of the Array constructor in the TypedArray constructor. The following code
shows the algorithm used in the Array class constructor, which you can reuse in your Array subclass constructor:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
public dynamic class Array
{
public function Array(...args)
{
var n:uint = args.length
if (n == 1 && (args[0] is Number))
{
var dlen:Number = args[0];
var ulen:uint = dlen;
if (ulen != dlen)
{
throw new RangeError("Array index is not a 32-bit unsigned integer ("+dlen+")");
}
length = ulen;
}
else
{
length = n;
for (var i:int=0; i < n; i++)
{
this[i] = args[i]
}
}
}
}
45
The TypedArray constructor shares most of the code from the Array constructor, with only four changes to the code.
First, the parameter list includes a new required parameter of type Class that allows specification of the array’s data
type. Second, the data type passed to the constructor is assigned to the
statement, the value of the
are the proper type. Fourth, the body of the
length property is assigned after the for loop so that length includes only arguments that
for loop uses the overridden version of the push() method so that only
dataType variable. Third, in the else
arguments of the correct data type are added to the array. The following example shows the TypedArray constructor
function:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
public dynamic class TypedArray extends Array
{
private var dataType:Class;
public function TypedArray(typeParam:Class, ...args)
{
dataType = typeParam;
var n:uint = args.length
if (n == 1 && (args[0] is Number))
{
var dlen:Number = args[0];
var ulen:uint = dlen
if (ulen != dlen)
{
throw new RangeError("Array index is not a 32-bit unsigned integer ("+dlen+")")
}
length = ulen;
}
else
{
for (var i:int=0; i < n; i++)
{
// type check done in push()
this.push(args[i])
}
length = this.length;
}
}
}
46
TypedArray overridden methods
The TypedArray class overrides the four methods of the Array class that are capable of adding elements to an array. In
each case, the overridden method adds a type check that prevents the addition of elements that are not the correct data
type. Subsequently, each method calls the superclass version of itself.
The push() method iterates through the list of arguments with a for..in loop and does a type check on each
argument. Any argument that is not the correct type is removed from the
for..in loop ends, the args array contains values only of type dataType. The superclass version of push() is then
the
called with the updated
AS3 override function push(...args):uint
{
for (var i:* in args)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
return (super.push.apply(this, args));
}
args array, as the following code shows:
args array with the splice() method. After
The concat() method creates a temporary TypedArray named passArgs to store the arguments that pass the type
check. This allows the reuse of the type check code that exists in the
args array, and calls push() on each argument. Because passArgs is typed as TypedArray, the TypedArray
the
version of
push() is executed. The concat() method then calls its own superclass version, as the following code
push() method. A for..in loop iterates through
shows:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
AS3 override function concat(...args):Array
{
var passArgs:TypedArray = new TypedArray(dataType);
for (var i:* in args)
{
// type check done in push()
passArgs.push(args[i]);
}
return (super.concat.apply(this, passArgs));
}
The splice() method takes an arbitrary list of arguments, but the first two arguments always refer to an index
number and the number of elements to delete. This is why the overridden
args array elements in index positions 2 or higher. One point of interest in the code is that there appears to be a
for
recursive call to
TypedArray, which means that the call to
for..in loop concludes, the args array contains only values of the correct type in index positions 2 or higher, and
splice() calls its own superclass version, as shown in the following code:
AS3 override function splice(...args):*
{
if (args.length > 2)
{
for (var i:int=2; i< args.length; i++)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
}
return (super.splice.apply(this, args));
}
splice() inside the for loop, but this is not a recursive call because args is of type Array rather than
args.splice() is a call to the superclass version of the method. After the
splice() method does type checking only
47
The unshift() method, which adds elements to the beginning of an array, also accepts an arbitrary list of arguments.
The overridden
unshift() method uses an algorithm very similar to that used by the push() method, as shown in
the following example code:
AS3 override function unshift(...args):uint
{
for (var i:* in args)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
return (super.unshift.apply(this, args));
}
}
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Arrays example: PlayList
Flash Player 9 and later, Adobe AIR 1.0 and later
The PlayList example demonstrates techniques for working with arrays, in the context of a music playlist application
that manages a list of songs. These techniques are:
• Creating an indexed array
• Adding items to an indexed array
• Sorting an array of objects by different properties, using different sorting options
• Converting an array to a character-delimited string
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The
PlayList application files can be found in the Samples/PlayList folder. The application consists of the following files:
FileDescription
48
PlayList.mxml
or
PlayList.fla
com/example/programmingas3/playlist/PlayList.asA class representing a list of songs. It uses an Array to store the list,
com/example/programmingas3/playlist/Song.asA value object representing information about a single song. The
com/example/programmingas3/playlist/SortProperty.asA pseudo-enumeration whose available values represent the
The main application file in Flash (FLA) or Flex (MXML).
and manages the sorting of the list’s items..
items that are managed by the PlayList class are Song instances.
properties of the Song class by which a list of Song objects can be
sorted.
PlayList class overview
Flash Player 9 and later, Adobe AIR 1.0 and later
The PlayList class manages a set of Song objects. It has public methods with functionality for adding a song to the
playlist (the
includes a read-only accessor property,
Internally, the PlayList class keeps track of its songs using a private Array variable:
public class PlayList
{
private var _songs:Array;
private var _currentSort:SortProperty = null;
private var _needToSort:Boolean = false;
...
}
addSong() method) and sorting the songs in the list (the sortList() method). In addition, the class
songList, which provides access to the actual set of songs in the playlist.
In addition to the _songs Array variable, which is used by the PlayList class to keep track of its list of songs, two other
private variables keep track of whether the list needs to be sorted (
sorted by at a given time (
_currentSort).
_needToSort) and which property the song list is
As with all objects, declaring an Array instance is only half the job of creating an Array. Before accessing an Array
instance’s properties or methods, it must be instantiated, which is done in the PlayList class’s constructor.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
public function PlayList()
{
this._songs = new Array();
// Set the initial sorting.
this.sortList(SortProperty.TITLE);
}
The first line of the constructor instantiates the _songs variable, so that it is ready to be used. In addition, the
sortList() method is called to set the initial sort-by property.
Adding a song to the list
Flash Player 9 and later, Adobe AIR 1.0 and later
When a user enters a new song into the application, the code in the data entry form calls the PlayList class’s addSong()
method.
/**
* Adds a song to the playlist.
*/
public function addSong(song:Song):void
{
this._songs.push(song);
this._needToSort = true;
}
49
Inside addSong(), the _songs array’s push() method is called, adding the Song object that was passed to addSong()
as a new element in that array. With the
of any sorting that might have been applied previously. This means that after the
list of songs is likely to no longer be sorted correctly, so the
sortList() method could be called immediately, removing the need to keep track of whether the list is sorted or not
push() method, the new element is added to the end of the array, regardless
push() method has been called, the
_needToSort variable is set to true. In theory, the
at a given time. In practice, however, there is no need for the list of songs to be sorted until immediately before it is
retrieved. By deferring the sorting operation, the application doesn’t perform sorting that is unnecessary if, for
example, several songs are added to the list before it is retrieved.
Sorting the list of songs
Flash Player 9 and later, Adobe AIR 1.0 and later
Because the Song instances that are managed by the playlist are complex objects, users of the application may wish to
sort the playlist according to different properties, such as song title or year of publication. In the PlayList application,
the task of sorting the list of songs has three parts: identifying the property by which the list should be sorted, indicating
what sorting options need to be used when sorting by that property, and performing the actual sort operation.
Properties for sorting
A Song object keeps track of several properties, including song title, artist, publication year, filename, and a userselected set of genres in which the song belongs. Of these, only the first three are practical for sorting. As a matter of
convenience for developers, the example includes the SortProperty class, which acts as an enumeration with values
representing the properties available for sorting.
public static const TITLE:SortProperty = new SortProperty("title");
public static const ARTIST:SortProperty = new SortProperty("artist");
public static const YEAR:SortProperty = new SortProperty("year");
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
The SortProperty class contain three constants, TITLE, ARTIST, and YEAR, each of which stores a String containing the
actual name of the associated Song class property that can be used for sorting. Throughout the rest of the code,
whenever a sort property is indicated, it is done using the enumeration member. For instance, in the PlayList
constructor, the list is sorted initially by calling the
// Set the initial sorting.
this.sortList(SortProperty.TITLE);
sortList() method, as follows:
Because the property for sorting is specified as SortProperty.TITLE, the songs are sorted according to their title.
Sorting by property and specifying sort options
The work of actually sorting the list of songs is performed by the PlayList class in the sortList() method, as follows:
/**
* Sorts the list of songs according to the specified property.
*/
public function sortList(sortProperty:SortProperty):void
{
...
var sortOptions:uint;
switch (sortProperty)
{
case SortProperty.TITLE:
sortOptions = Array.CASEINSENSITIVE;
break;
case SortProperty.ARTIST:
sortOptions = Array.CASEINSENSITIVE;
break;
case SortProperty.YEAR:
sortOptions = Array.NUMERIC;
break;
}
// Perform the actual sorting of the data.
this._songs.sortOn(sortProperty.propertyName, sortOptions);
// Save the current sort property.
this._currentSort = sortProperty;
// Record that the list is sorted.
this._needToSort = false;
}
50
When sorting by title or artist, it makes sense to sort alphabetically, but when sorting by year, it’s most logical to
perform a numeric sort. The
sortOptions, according to the value specified in the sortProperty parameter. Here again the named enumeration
switch statement is used to define the appropriate sorting option, stored in the variable
members are used to distinguish between properties, rather than hard-coded values.
With the sort property and sort options determined, the _songs array is actually sorted by calling its sortOn()
method, passing those two values as parameters. The current sort property is recorded, as is the fact that the song list
is currently sorted.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with arrays
Combining array elements into a character-delimited string
Flash Player 9 and later, Adobe AIR 1.0 and later
In addition to using an array to maintain the song list in the PlayList class, in this example arrays are also used in the
Song class to help manage the list of genres to which a given song belongs. Consider this snippet from the Song class’s
definition:
private var _genres:String;
public function Song(title:String, artist:String, year:uint, filename:String, genres:Array)
{
...
// Genres are passed in as an array
// but stored as a semicolon-separated string.
this._genres = genres.join(";");
}
When creating a new Song instance, the genres parameter that is used to specify the genre (or genres) the song
belongs to is defined as an Array instance. This makes it convenient to group multiple genres together into a single
variable that can be passed to the constructor. However, internally the Song class maintains the genres in the private
_genres variable as a semicolon-separated String instance. The Array parameter is converted into a semicolon-
separated string by calling its
join() method with the literal string value ";" as the specified delimiter.
51
By the same token, the genres accessors allow genres to be set or retrieved as an Array:
public function get genres():Array
{
// Genres are stored as a semicolon-separated String,
// so they need to be transformed into an Array to pass them back out.
return this._genres.split(";");
}
public function set genres(value:Array):void
{
// Genres are passed in as an array,
// but stored as a semicolon-separated string.
this._genres = value.join(";");
}
The genresset accessor behaves exactly the same as the constructor; it accepts an Array and calls the join() method
to convert it to a semicolon-separated String. The
variable’s
string value
split() method is called, splitting the String into an array of values using the specified delimiter (the literal
";" as before).
get accessor performs the opposite operation: the _genres
Last updated 3/21/2011
Chapter 4: Handling errors
Flash Player 9 and later, Adobe AIR 1.0 and later
To “handle” an error means that you build logic into your application to respond to, or fix, an error. Errors are
generated either when an application is compiled or when a compiled application is running. When your application
handles errors, something occurs as a response when the error is encountered, as opposed to no response (when
whatever process created the error fails silently). Used correctly, error handling helps shield your application and its
users from otherwise unexpected behavior.
However, error handling is a broad category that includes responding to many kinds of errors that are thrown during
compilation or while an application is running. This discussion focuses on how to handle run-time errors (thrown
while an application is running), the different types of errors that can be generated, and the advantages of the errorhandling system in ActionScript 3.0.
Basics of error handling
52
Flash Player 9 and later, Adobe AIR 1.0 and later
A run-time error is something that goes wrong in your ActionScript code that stops the ActionScript content from
running as intended. To ensure that your ActionScript code runs smoothly for users, write code in your application
that handles the error—that fixes it, works around it, or at least lets the user know that it has happened. This process
is called error handling.
Error handling is a broad category that includes responding to many kinds of errors that are thrown during
compilation or while an application is running. Errors that happen at compile time are often easier to identify— fix
them to complete the process of creating a SWF file.
Run-time errors can be more difficult to detect, because in order for them to occur the erroneous code must actually
be run. If a segment of your program has several branches of code, like an
possible condition, with all the possible input values that real users might use, to confirm that your code is error-free.
Run-time errors can be divided into two categories: program errors are mistakes in your ActionScript code, such as
specifying the wrong data type for a method parameter; logical errors are mistakes in the logic (the data checking and
value manipulation) of your program, such as using the wrong formula to calculate interest rates in a banking
application. Again, both of these types of errors can often be detected and corrected ahead of time by diligently testing
your application.
Ideally, you’ll want to identify and remove all errors from your application before it is released to end users. However,
not all errors can be foreseen or prevented. For example, suppose your ActionScript application loads information
from a particular website that is outside your control. If at some point that website isn’t available, the part of your
application that depends on that external data won’t behave correctly. The most important aspect of error handling
involves preparing for these unknown cases and handling them gracefully. Users need to continue to use your
application, or at least get a friendly error message explaining why it isn’t working.
if..then..else statement, test every
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Run-time errors are represented in two ways in ActionScript:
• Error classes: Many errors have an error class associated with them. When an error occurs, the Flash runtime (such
as Flash Player or Adobe AIR) creates an instance of the specific error class that is associated with that particular
error. Your code can use the information contained in that error object to make an appropriate response to the
error.
• Error events: Sometimes an error occurs when the Flash runtime would normally trigger an event. In those cases,
an error event is triggered instead. Each error event has a class associated with it, and the Flash runtime passes an
instance of that class to the methods that are subscribed to the error event.
To determine whether a particular method can trigger an error or error event, see the method’s entry in the
ActionScript 3.0 Reference for the Adobe Flash Platform.
Important concepts and terms
The following reference list contains important terms for programming error handling routines:
Asynchronous A program command such as a method call that doesn’t provide an immediate result; instead it gives
a result (or error) in the form of an event.
Catch When an exception (a run-time error) occurs and your code becomes aware of the exception, that code is said
to catch the exception. Once an exception is caught, the Flash runtime stops notifying other ActionScript code of the
exception.
53
Debugger version A special version of the Flash runtime, such as the Flash Player dubugger version or the AIR Debug
Launcher (ADL), that contains code for notifying users of run-time errors. In the standard version of Flash Player or
Adobe AIR (the one that most users have), errors that aren’t handled by your ActionScript code are ignored. In the
debugger versions (which are included with Adobe Flash CS4 Professional and Adobe Flash Builder), a warning
message appears when an unhandled error happens.
Exception An error that happens while an application is running and that the Flash runtime can’t resolve on its own.
Re-throw When your code catches an exception, the Flash runtime no longer notifies other objects of the exception.
If it’s important for other objects to receive the exception, your code must re-throw the exception to start the
notification process again.
Synchronous A program command, such as a method call, that provides an immediate result (or immediately throws
an error), meaning that the response can be used within the same code block.
Throw The act of notifying a Flash runtime (and consequently, notifying other objects and ActionScript code) that an
error has occurred is known as throwing an error.
Types of errors
Flash Player 9 and later, Adobe AIR 1.0 and later
When you develop and run applications, you encounter different types of errors and error terminology. The following
list introduces the major error types and terms:
• Compile-time errors are raised by the ActionScript compiler during code compilation. Compile-time errors occur
when syntactical problems in your code prevent your application from being built.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
• Run-time errors occur when you run your application after you compile it. Run-time errors represent errors that
are caused while a SWF file plays in a Flash runtime (such as Adobe Flash Player or Adobe AIR). In most cases, you
handle run-time errors as they occur, reporting them to the user and taking steps to keep your application running.
If the error is a fatal error, such as not being able to connect to a remote website or load required data, you can use
error handling to allow your application to finish, gracefully.
• Synchronous errors are run-time errors that occur at the time a function is called—for example, when you try to use
a specific method and the argument you pass to the method is invalid, so the Flash runtime throws an exception.
Most errors occur synchronously—at the time the statement executes—and the flow of control passes immediately
to the most applicable
catch statement.
For example, the following code excerpt throws a run-time error because the browse() method is not called before
the program attempts to upload a file:
var fileRef:FileReference = new FileReference();
try
{
fileRef.upload(new URLRequest("http://www.yourdomain.com/fileupload.cfm"));
}
catch (error:IllegalOperationError)
{
trace(error);
// Error #2037: Functions called in incorrect sequence, or earlier
// call was unsuccessful.
}
54
In this case, a run-time error is thrown synchronously because Flash Player determined that the browse() method
was not called before the file upload was attempted.
For detailed information on synchronous error handling, see “Handling synchronous errors in an application” on
page 58.
• Asynchronouserrors are run-time errors that occur at various points during runtime; they generate events and event
listeners catch them. An asynchronous operation is one in which a function initiates an operation, but doesn’t wait
for it to complete. You can create an error event listener to wait for the application or user to try some operation.
If the operation fails, you catch the error with an event listener and respond to the error event. Then, the event
listener calls an event handler function to respond to the error event in a useful manner. For example, the event
handler could launch a dialog box that prompts the user to resolve the error.
Consider the file-upload synchronous error example presented earlier. If you successfully call the browse()
method before beginning a file upload, Flash Player would dispatch several events. For example, when an upload
starts, the
open event is dispatched. When the file upload operation completes successfully, the complete event is
dispatched. Because event handling is asynchronous (that is, it does not occur at specific, known, predesignated
times), use the
addEventListener() method to listen for these specific events, as the following code shows:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.OPEN, openHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
fileRef.browse();
function selectHandler(event:Event):void
{
trace("...select...");
var request:URLRequest = new URLRequest("http://www.yourdomain.com/fileupload.cfm");
request.method = URLRequestMethod.POST;
event.target.upload(request);
}
function openHandler(event:Event):void
{
trace("...open...");
}
function completeHandler(event:Event):void
{
trace("...complete...");
}
For detailed information on asynchronous error handling, see “Responding to error events and status” on page 63.
55
• Uncaught exceptions are errors thrown with no corresponding logic (like a catch statement) to respond to them.
If your application throws an error, and no appropriate
catch statement or event handler can be found at the
current or higher level to handle the error, the error is considered an uncaught exception.
When an uncaught error happens, the runtime dispatches an uncaughtError event. This event is also known as a
“global error handler.” This event is dispatched by the SWF’s UncaughtErrorEvents object, which is available
through the
LoaderInfo.uncaughtErrorEvents property. If no listeners are registered for the uncaughtError
event, the runtime ignores uncaught errors and tries to continue running, as long as the error doesn’t stop the SWF.
In addition to dispatching the uncaughtError event, debugger versions of the Flash runtime respond to uncaught
errors by terminating the current script. Then, they display the uncaught error in
trace statement output or
writing the error message to a log file. If the exception object is an instance of the Error class or one of its subclasses,
getStackTrace() method is called. The stack trace information is also displayed in trace statement output or
the
in a log file. For more information about using the debugger version of Flash runtimes, see
“Working with the
debugger versions of Flash runtimes” on page 57.
Note: While processing an uncaughtError event, if an error event is thrown from an uncaughtError handler, the event
handler is called multiple times. This results in an infinite loop of exceptions. It is recommended that you avoid such
a scenario.
Error handling in ActionScript 3.0
Flash Player 9 and later, Adobe AIR 1.0 and later
Since many applications can run without building the logic to handle errors, developers are tempted to postpone
building error handling into their applications. However, without error handling, an application can easily stall or
frustrate the user if something doesn’t work as expected. ActionScript 2.0 has an Error class that allows you to build
logic into custom functions to throw an exception with a specific message. Because error handling is critical for making
a user-friendly application, ActionScript 3.0 includes an expanded architecture for catching errors.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Note: While the ActionScript 3.0 Reference for the Adobe Flash Platform documents the exceptions thrown by many
methods, it might not include all possible exceptions for each method. A method might throw an exception for syntax
errors or other problems that are not noted explicitly in the method description, even when the description does list some
of the exceptions a method throws.
ActionScript 3.0 error-handling elements
Flash Player 9 and later, Adobe AIR 1.0 and later
ActionScript 3.0 includes many tools for error handling, including:
• Error classes. ActionScript 3.0 includes a broad range of Error classes to expand the scope of situations that can
produce error objects. Each Error class helps applications handle and respond to specific error conditions, whether
they are related to system errors (like a MemoryError condition), coding errors (like an ArgumentError condition),
networking and communication errors (like a URIError condition), or other situations. For more information on
each class, see
• Fewer silent failures. In earlier versions of Flash Player, errors were generated and reported only if you explicitly
used the
throw run-time errors. These errors allow you to handle these exceptions more effectively when they occur, then
react to each exception, individually.
• Clear error messages displayed during debugging. When you are using the debugger version of a Flash runtime,
problematic code or situations generate robust error messages, which help you easily identify reasons why a
particular block of code fails. These messages make fixing errors more efficient. For more information, see
“Working with the debugger versions of Flash runtimes” on page 57.
• Precise errors allow for clear error messages displayed to users. In previous versions of Flash Player, the
FileReference.upload() method returned a Boolean value of false if the upload() call was unsuccessful,
indicating one of five possible errors. If an error occurs when you call the
four specific errors help you display more accurate error messages to end users.
• Refined error handling. Distinct errors are thrown for many common situations. For example, in ActionScript 2.0,
before a FileReference object has been populated, the
display the
name property before it has been populated, Flash Player or AIR throws an IllegalOperationError, which
the
informs you that the value has not been set, and you can use
more information see
• No significant performance drawbacks. Using try..catch..finally blocks to handle errors takes little or no
additional resources compared to previous versions of ActionScript.
• An ErrorEvent class that allows you to build listeners for specific asynchronous error events. For more information
“Responding to error events and status” on page 63.
see
“Comparing the Error classes” on page 66.
throw statement. For Flash Player 9 and later Flash runtimes, native ActionScript methods and properties
upload() method in ActionScript 3.0,
name property has the value null (so, before you can use or
name property, ensure that the value is set and not null). In ActionScript 3.0, if you attempt to access
try..catch..finally blocks to handle the error. For
“Using try..catch..finally statements” on page 58.
56
Error-handling strategies
Flash Player 9 and later, Adobe AIR 1.0 and later
As long as your application doesn’t encounter a problematic condition, it can still run successfully if you don’t build
error-handling logic into your code. However, if you don’t actively handle errors and your application does encounter
a problem, your users will never know why your application fails when it does.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
There are different ways you can approach error handling in your application. The following list summarizes the three
major options for handling errors:
• Use try..catch..finally statements. These statements catch synchronous errors as they occur. You can nest
your statements into a hierarchy to catch exceptions at various levels of code execution. For more information, see
“Using try..catch..finally statements” on page 58.
• Create your own custom error objects. You can use the Error class to create your own custom error objects to track
specific operations in your application that are not covered by built-in error types. Then you can use
try..catch..finally statements on your custom error objects. For more information see “Creating custom
error classes” on page 62.
• Write event listeners and handlers to respond to error events. By using this strategy, you can create global error
handlers that let you handle similar events without duplicating much code in
are also more likely to catch asynchronous errors using this approach. For more information, see
try..catch..finally blocks. You
“Responding to
error events and status” on page 63.
Working with the debugger versions of Flash runtimes
Flash Player 9 and later, Adobe AIR 1.0 and later
57
Adobe provides developers with special editions of the Flash runtimes to assist debugging efforts. You obtain a copy
of the debugger version of Flash Player when you install Adobe Flash Professional or Adobe Flash Builder. You also
obtain a utility for the debugging of Adobe AIR applications, which is called ADL, when you install either of those
tools, or as part of the Adobe AIR SDK.
There is a notable difference in how the debugger versions and the release versions of Flash Player and Adobe AIR
indicate errors. The debugger versions shows the error type (such as a generic Error, IOError, or EOFError), error
number, and a human-readable error message. The release versions shows only the error type and error number. For
example, consider the following code:
If the readBoolean() method throws an EOFError in the debugger version of Flash Player, the following message
displays in the
tf text field: “EOFError: Error #2030: End of file was encountered.”
The same code in a release version of Flash Player or Adobe AIR would display the following text: “EOFError: Error
#2030.”
Note: The debugger players broadcast an event named "allComplete"; avoid creating custom events with the name
“allComplete”. Otherwise, you will encounter unpredictable behavior when debugging.
To keep resources and size to a minimum in the release versions, error message strings are not present. You can look
up the error number in the documentation (the appendixes of the
ActionScript 3.0 Reference for the Adobe Flash
Platform) to correlate to an error message. Alternatively, you can reproduce the error using the debugger versions of
Flash Player and AIR to see the full message.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Handling synchronous errors in an application
Flash Player 9 and later, Adobe AIR 1.0 and later
The most common error handling is synchronous error-handling logic, where you insert statements into your code to
catch synchronous errors while an application is running. This type of error handling lets your application notice and
recover from run-time errors when functions fail. The logic for catching a synchronous error includes
try..catch..finally statements, which literally try an operation, catch any error response from the Flash runtime,
and finally execute some other operation to handle the failed operation.
Using try..catch..finally statements
Flash Player 9 and later, Adobe AIR 1.0 and later
When you work with synchronous run-time errors, use the try..catch..finally statements to catch errors. When
a run-time error occurs, the Flash runtime throws an exception, which means that it suspends normal execution and
creates a special object of type Error. The Error object is then thrown to the first available
The try statement encloses statements that have the potential to create errors. You always use the catch statement
try statement. If an error is detected in one of the statements in the try statement block, the catch statements
with a
that are attached to that
try statement run.
catch block.
58
The finally statement encloses statements that run whether an error occurs in the try block. If there is no error, the
statements within the
appropriate
catch statement executes first, followed by the statements in the finally block.
finally block execute after the try block statements complete. If there is an error, the
The following code demonstrates the syntax for using the try..catch..finally statements:
try
{
// some code that could throw an error
}
catch (err:Error)
{
// code to react to the error
}
finally
{
// Code that runs whether an error was thrown. This code can clean
// up after the error, or take steps to keep the application running.
}
Each catch statement identifies a specific type of exception that it handles. The catch statement can specify only error
classes that are subclasses of the Error class. Each
catch statement is checked in order. Only the first catch statement
that matches the type of error thrown runs. In other words, if you first check the higher-level Error class and then a
subclass of the Error class, only the higher-level Error class matches. The following code illustrates this point:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
try
{
throw new ArgumentError("I am an ArgumentError");
}
catch (error:Error)
{
trace("<Error> " + error.message);
}
catch (error:ArgumentError)
{
trace("<ArgumentError> " + error.message);
}
The previous code displays the following output:
<Error> I am an ArgumentError
To correctly catch the ArgumentError, make sure that the most specific error types are listed first and the more generic
error types are listed later, as the following code shows:
try
{
throw new ArgumentError("I am an ArgumentError");
}
catch (error:ArgumentError)
{
trace("<ArgumentError> " + error.message);
}
catch (error:Error)
{
trace("<Error> " + error.message);
}
59
Several methods and properties in the ActionScript API throw run-time errors if they encounter errors while they
execute. For example, the
close() method in the Sound class throws an IOError if the method is unable to close the
audio stream, as demonstrated in the following code:
var mySound:Sound = new Sound();
try
{
mySound.close();
}
catch (error:IOError)
{
// Error #2029: This URLStream object does not have an open stream.
}
As you become more familiar with the ActionScript 3.0 Reference for the Adobe Flash Platform, you’ll notice which
methods throw exceptions, as detailed in each method’s description.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
The throw statement
Flash Player 9 and later, Adobe AIR 1.0 and later
Flash runtimes throw exceptions when they encounter errors in your running application. In addition, you can
explicitly throw exceptions yourself using the
that you throw instances of the Error class or its subclasses. The following code demonstrates a
throws an instance of the Error class,
MyErr, and eventually calls a function, myFunction(), to respond after the error
is thrown:
var MyError:Error = new Error("Encountered an error with the numUsers value", 99);
var numUsers:uint = 0;
try
{
if (numUsers == 0)
{
trace("numUsers equals 0");
}
}
catch (error:uint)
{
throw MyError; // Catch unsigned integer errors.
}
catch (error:int)
{
throw MyError; // Catch integer errors.
}
catch (error:Number)
{
throw MyError; // Catch number errors.
}
catch (error:*)
{
throw MyError; // Catch any other error.
}
finally
{
myFunction(); // Perform any necessary cleanup here.
}
throw statement. When explicitly throwing errors, Adobe recommends
throw statement that
60
Notice that the catch statements are ordered so that the most specific data types are listed first. If the catch statement
for the Number data type is listed first, neither the catch statement for the uint data type nor the catch statement for
the int data type is ever run.
Note: In the Java programming language, each function that can throw an exception must declare this fact, listing the
exception classes it can throw in a
throws clause attached to the function declaration. ActionScript does not require you
to declare the exceptions thrown by a function.
Displaying a simple error message
Flash Player 9 and later, Adobe AIR 1.0 and later
One of the biggest benefits of the new exception and error event model is that it allows you to tell users when and why
an action has failed. Your part is to write the code to display the message and offer options in response.
The following code shows a simple try..catch statement to display the error in a text field:
public class SimpleError extends Sprite
{
public var employee:XML =
<EmpCode>
<costCenter>1234</costCenter>
<costCenter>1-234</costCenter>
</EmpCode>;
public function SimpleError()
{
try
{
if (employee.costCenter.length() != 1)
{
throw new Error("Error, employee must have exactly one cost center assigned.");
}
}
catch (error:Error)
{
var errorMessage:TextField = new TextField();
errorMessage.autoSize = TextFieldAutoSize.LEFT;
errorMessage.textColor = 0xFF0000;
errorMessage.text = error.message;
addChild(errorMessage);
}
}
}
}
61
Using a wider range of error classes and built-in compiler errors, ActionScript 3.0 offers more information than
previous versions of ActionScript about why something has failed. This information enables you to build more stable
applications with better error handling.
Rethrowing errors
Flash Player 9 and later, Adobe AIR 1.0 and later
When you build applications, there are several occasions in which you need to rethrow an error if you are unable to
handle the error properly. For example, the following code shows a nested
custom ApplicationError if the nested
The output from the previous snippet would be the following:
<< try >>
<< catch >> ApplicationError: some error which will be rethrown
<< throw >>
<< catch >> ApplicationError: some error which will be rethrown
The nested try block throws a custom ApplicationError error that is caught by the subsequent catch block. This
catch block can try to handle the error, and if unsuccessful, throw the ApplicationError object to the enclosing
nested
try..catch block.
Creating custom error classes
Flash Player 9 and later, Adobe AIR 1.0 and later
You can extend one of the standard Error classes to create your own specialized error classes in ActionScript. There
are a number of reasons to create your own error classes:
• To identify specific errors or groups of errors that are unique to your application.
For example, take different actions for errors thrown by your own code, in addition to those errors trapped by a
Flash runtime. You can create a subclass of the Error class to track the new error data type in
• To provide unique error display capabilities for errors generated by your application.
For example, you can create a new toString() method that formats your error messages in a certain way. You can
also define a
lookupErrorString() method that takes an error code and retrieves the proper message based on
the user’s language preference.
try..catch blocks.
A specialized error class must extend the core ActionScript Error class. Here is an example of a specialized AppError
class that extends the Error class:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
public class AppError extends Error
{
public function AppError(message:String, errorID:int)
{
super(message, errorID);
}
}
The following shows an example of using AppError in your project:
Note: If you want to override the Error.toString() method in your subclass, give it one ...(rest) parameter. The
ECMAScript language specification on which ActionScript 3.0 is based defines the
Error.toString() method that way,
and ActionScript 3.0 defines it the same way for backward compatibility. Therefore, when you override the
Error.toString() method, match the parameters exactly. You do not want to pass any parameters to your
toString() method at runtime, because those parameters are ignored.
63
Responding to error events and status
Flash Player 9 and later, Adobe AIR 1.0 and later
One of the most noticeable improvements to error handling in ActionScript 3.0 is the support for error event handling
for responding to asynchronous errors while an application is running. (For a definition of asynchronous errors, see
“Types of errors” on page 53.)
You can create event listeners and event handlers to respond to the error events. Many classes dispatch error events
the same way they dispatch other events. For example, an instance of the XMLSocket class normally dispatches three
types of events:
XMLSocket class can dispatch the
more information about event listeners and event handlers, see
Error events fit into one of two categories:
• Error events that extend the ErrorEvent class
The flash.events.ErrorEvent class contains the properties and methods for managing errors related to networking
and communication operations in a running application. The AsyncErrorEvent, IOErrorEvent, and
SecurityErrorEvent classes extend the ErrorEvent class. If you’re using the debugger version of a Flash runtime, a
dialog box informs you at run-time of any error events without listener functions that the player encounters.
• Status-based error events
The status-based error events are related to the netStatus and status properties of the networking and
communication classes. If a Flash runtime encounters a problem when reading or writing data, the value of the
netStatus.info.level or status.level properties (depending on the class object you’re using) is set to the
value
event handler function.
Event.CLOSE, Event.CONNECT, and DataEvent.DATA. However, when a problem occurs, the
IOErrorEvent.IOError or the SecurityErrorEvent.SECURITY_ERROR. For
“Handling events” on page 117.
"error". You respond to this error by checking if the level property contains the value "error" in your
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Working with error events
Flash Player 9 and later, Adobe AIR 1.0 and later
The ErrorEvent class and its subclasses contain error types for handling errors dispatched by Flash runtimes as they
try to read or write data.
The following example uses both a try..catch statement and error event handlers to display any errors detected
while trying to read a local file. You can add more sophisticated handling code to provide a user with options or
otherwise handle the error automatically in the places indicated by the comment “your error-handling code here”:
{
trace(err.message);
// your error-handling code here
}
myMP3.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
}
private function linkHandler(linkEvent:TextEvent):void
{
playMP3(linkEvent.text);
// your error-handling code here
}
private function errorHandler(errorEvent:IOErrorEvent):void
{
trace(errorEvent.text);
// your error-handling code here
}
}
}
Working with status change events
Flash Player 9 and later, Adobe AIR 1.0 and later
65
Flash runtimes dynamically change the value of the netStatus.info.level or status.level properties for the
classes that support the
netStatus.info.level property are NetConnection, NetStream, and SharedObject. The classes that have the
status.level property are HTTPStatusEvent, Camera, Microphone, and LocalConnection. You can write a handler
function to respond to the change in
level property while an application is running. The classes that have the
level value and track communication errors.
The following example uses a netStatusHandler() function to test the value of the level property. If the level
property indicates that an error has been encountered, the code traces the message “Video stream failed”.
public class VideoExample extends Sprite
{
private var videoUrl:String = "Video.flv";
private var connection:NetConnection;
private var stream:NetStream;
public function VideoExample()
{
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
connection.connect(null);
}
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
private function netStatusHandler(event:NetStatusEvent):void
{
if (event.info.level == "error")
{
trace("Video stream failed")
}
else
{
connectStream();
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + event);
}
private function connectStream():void
{
var stream:NetStream = new NetStream(connection);
var video:Video = new Video();
video.attachNetStream(stream);
stream.play(videoUrl);
addChild(video);
}
}
}
66
Comparing the Error classes
Flash Player 9 and later, Adobe AIR 1.0 and later
ActionScript provides a number of predefined Error classes. But, you can also use the same Error classes in your own
code. There are two main types of Error classes in ActionScript 3.0: ActionScript core Error classes and flash.error
package Error classes. The flash.error package contains additional classes to aid ActionScript 3.0 application
development and debugging.
Core Error classes
Flash Player 9 and later, Adobe AIR 1.0 and later
The core error classes include the Error, ArgumentError, EvalError, RangeError, ReferenceError, SecurityError,
SyntaxError, TypeError, URIError, and VerifyError classes. Each of these classes are located in the top-level
namespace.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Class nameDescriptionNotes
67
ErrorThe Error class is for throwing exceptions, and is the
ArgumentErrorThe ArgumentError class represents an error that
EvalErrorAn EvalError exception is thrown if any parameters
RangeErrorA RangeError exception is thrown if a numeric value
ReferenceErrorA ReferenceError exception is thrown when a
base class for the other exception classes defined in
ECMAScript: EvalError, RangeError, ReferenceError,
SyntaxError, TypeError, and URIError.
occurs when the parameter values supplied during a
function call do not match the parameters defined for
that function.
are passed to the Function class’s constructor or if
user code calls the
falls outside an acceptable range.
reference to an undefined property is attempted on a
sealed (nondynamic) object. Versions of the
ActionScript compiler before ActionScript 3.0 did not
throw an error when access was attempted to a
property that was
3.0 throws the ReferenceError exception in this
condition.
eval() function.
undefined. However ActionScript
The Error class serves as the base class for all run-time errors,
and is the recommended base class for any custom error
classes.
Some examples of argument errors include the following:
• Too few or too many arguments are supplied to a method.
• An argument was expected to be a member of an
enumeration and was not.
In ActionScript 3.0, support for the eval() function has been
removed and attempts to use the function result in an error.
Earlier versions of Flash Player used the eval() function to
access variables, properties, objects, or movie clips by name.
For example, a RangeError is thrown by the Timer class if a delay
was either negative or was not finite. A RangeError could also be
thrown if you attempted to add a display object at an invalid
depth.
Exceptions for undefined variables point to potential bugs,
helping you improve software quality. However, if you are not
used to having to initialize your variables, this new ActionScript
behavior requires some changes in your coding habits.
SecurityErrorThe SecurityError exception is thrown when a security
violation takes place and access is denied.
SyntaxErrorA SyntaxError exception is thrown when a parsing
error occurs in your ActionScript code.
Some examples of security errors include the following:
• An unauthorized property access or method call is made
across a security sandbox boundary.
• An attempt was made to access a URL not permitted by the
security sandbox.
• A socket connection was attempted to a port but the
necessary socket policy file wasn’t present.
• An attempt was made to access the user's camera or
microphone, and the user denide the access to the device .
A SyntaxError can be thrown under the following
circumstances:
• ActionScript throws SyntaxError exceptions when the
RegExp class parses an invalid regular expression.
• ActionScript throws SyntaxError exceptions when the
XMLDocument class parses invalid XML.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Class nameDescriptionNotes
68
TypeErrorThe TypeError exception is thrown when the actual
type of an operand is different from the expected
type.
URIErrorThe URIError exception is thrown when one of the
global URI handling functions is used in a way that is
incompatible with its definition.
VerifyErrorA VerifyError exception is thrown when a malformed
or corrupted SWF file is encountered.
flash.error package Error classes
Flash Player 9 and later, Adobe AIR 1.0 and later
A TypeError can be thrown under the following circumstances:
• An actual parameter of a function or method could not be
coerced to the formal parameter type.
• A value is assigned to a variable and cannot be coerced to the
variable’s type.
• The right side of the is or instanceof operator is not a
valid type.
• The super keyword is used illegally.
• A property lookup results in more than one binding, and is
therefore ambiguous.
• A method is called on an incompatible object. For example, a
TypeError exception is thrown if a method in the RegExp class
is “grafted” onto a generic object and then called.
A URIError can be thrown under the following circumstances:
An invalid URI is specified for a Flash Player API function that
expects a valid URI, such as
When a SWF file loads another SWF file, the parent SWF file can
catch a VerifyError generated by the loaded SWF file.
Socket.connect().
The flash.error package contains Error classes that are considered part of the Flash runtime API. In contrast to the
Error classes described, the flash.error package communicates errors events that are specific to Flash runtimes (such
as Flash Player and Adobe AIR).
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Class nameDescriptionNotes
69
EOFErrorAn EOFError exception is thrown when you
attempt to read past the end of the available data.
IllegalOperationErrorAn IllegalOperationError exception is thrown
when a method is not implemented or the
implementation doesn't cover the current usage.
IOErrorAn IOError exception is thrown when some type of
I/O exception occurs.
MemoryErrorA MemoryError exception is thrown when a
memory allocation request fails.
For example, an EOFError is thrown when one of the
read methods in the IDataInput interface is called and
there is insufficient data to satisfy the read request.
Examples of illegal operation error exceptions include
the following:
• A base class, such as DisplayObjectContainer,
provides more functionality than the Stage can
support. For example, if you attempt to get or set a
mask on the Stage (using
runtime throws an IllegalOperationError with the
message “The Stage class does not implement this
property or method.”
stage.mask), the Flash
• A subclass inherits a method it does not require and
does not want to support.
• Certain accessibility methods are called when Flash
Player is compiled without accessibility support.
• Authoring-only features are called from a run-time
version of Flash Player.
• You attempt to set the name of an object placed on
the timeline.
You get this error, for example, when a read-write
operation is attempted on a socket that is not
connected or that has become disconnected.
By default, ActionScript Virtual Machine 2 does not
impose a limit on how much memory an ActionScript
program allocates. On a desktop system, memory
allocation failures are infrequent. You see an error
thrown when the system is unable to allocate the
memory required for an operation. So, on a desktop
system, this exception is rare unless an allocation
request is extremely large; for example, a request for 3
billion bytes is impossible because a 32-bit Microsoft
Windows
® program can access only 2 GB of address
space.
®
ScriptTimeoutErrorA ScriptTimeoutError exception is thrown when a
script timeout interval of 15 seconds is reached. By
catching a ScriptTimeoutError exception, you can
handle the script timeout more gracefully. If there
is no exception handler, the uncaught exception
handler displays a dialog box with an error
message.
StackOverflowErrorThe StackOverflowError exception is thrown when
the stack available to the script has been
exhausted.
Last updated 3/21/2011
To prevent a malicious developer from catching the
exception and staying in an infinite loop, only the first
ScriptTimeoutError exception thrown in the course of
a particular script can be caught. A subsequent
ScriptTimeoutError exception cannot be caught by
your code and immediately goes to the uncaught
exception handler.
A StackOverflowError exception might indicate that
infinite recursion has occurred.
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
Handling errors example: CustomErrors application
Flash Player 9 and later, Adobe AIR 1.0 and later
The CustomErrors application demonstrates techniques for working with custom errors when building an
application. These techniques are:
• Validating an XML packet
• Writing a custom error
• Throwing custom errors
• Notifying users when an error is thrown
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The
CustomErrors application files can be found in the Samples/CustomError folder. The application consists of the
following files:
FileDescription
70
CustomErrors.mxml
or
CustomErrors.fla
com/example/programmingas3/errors/ApplicationError.asA class that serves as the base error class for both the FatalError and
com/example/programmingas3/errors/FatalError.asA class that defines a FatalError errorthrown by the application. This class
com/example/programmingas3/errors/Validator.asA class that defines a single method that validates a user-supplied
com/example/programmingas3/errors/WarningError.asA class that defines a WarningError error thrown by the application. This
The main application file in Flash (FLA) or Flex (MXML)
WarningError classes.
extends the custom ApplicationError class.
employee XML packet.
class extends the custom ApplicationError class.
CustomErrors application overview
Flash Player 9 and later, Adobe AIR 1.0 and later
When the application loads, the initApp() method is called for Flex applications or the timeline (non-function) code
is executed for Flash Professional applications. This code defines a sample XML packet to be verified by the Validator
class. The following code is run:
The XML packet is later displayed in a TextArea component instance on the Stage. This step allows you to modify the
XML packet before attempting to revalidate it.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
When the user clicks the Validate button, the validateData() method is called. This method validates the employee
XML packet using the
validateData() method:
function validateData():void
{
try
{
var tempXML:XML = XML(xmlText.text);
Validator.validateEmployeeXML(tempXML);
status.text = "The XML was successfully validated.";
}
catch (error:FatalError)
{
showFatalError(error);
}
catch (error:WarningError)
{
showWarningError(error);
}
catch (error:Error)
{
showGenericError(error);
}
}
validateEmployeeXML() method in the Validator class. The following code shows the
71
First, a temporary XML object is created using the contents of the TextArea component instance xmlText. Next, the
validateEmployeeXML() method in the custom Validator class (com.example.programmingas3/errors/Validator.as)
is called and passes the temporary XML object as a parameter. If the XML packet is valid, the
instance displays a success message and the application exits. If the
validateEmployeeXML() method throws a
custom error (that is, a FatalError, WarningError, or a generic Error occurs), the appropriate
executes and calls either the
these methods displays an appropriate message in a text area named
that occurred. Each method also updates the
showFatalError(), showWarningError(), or showGenericError() methods. Each of
statusText to notify the user of the specific error
status Label component instance with a specific message.
status Label component
catch statement
If a fatal error occurs during an attempt to validate the employee XML packet, the error message is displayed in the
statusText text area, and the xmlText TextArea component instance and validateBtn Button component instance
are disabled, as the following code shows:
function showFatalError(error:FatalError):void
{
var message:String = error.message + "\n\n";
var title:String = error.getTitle();
statusText.text = message + " " + title + "\n\nThis application has ended.";
this.xmlText.enabled = false;
this.validateBtn.enabled = false;
hideButtons();
}
If a warning error instead of a fatal error occurs, the error message is displayed in the statusText TextArea instance,
xmlText TextField and Button component instances aren’t disabled. The showWarningError() method
but the
displays the custom error message in the
to proceed with validating the XML or cancel the script. The following excerpt shows the
statusText text area. The message also asks the user to decide if they want
showWarningError()
method:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
function showWarningError(error:WarningError):void
{
var message:String = error.message + "\n\n" + "Do you want to exit this application?";
showButtons();
var title:String = error.getTitle();
statusText.text = message;
}
When the user clicks either the Yes or No button, the closeHandler() method is called. The following excerpt shows
closeHandler() method:
the
function closeHandler(event:CloseEvent):void
{
switch (event.detail)
{
case yesButton:
showFatalError(new FatalError(9999));
break;
case noButton:
statusText.text = "";
hideButtons();
break;
}
}
72
If the user chooses to cancel the script by clicking Yes, a FatalError is thrown, causing the application to terminate.
Building a custom validator
Flash Player 9 and later, Adobe AIR 1.0 and later
The custom Validator class contains a single method, validateEmployeeXML(). The validateEmployeeXML()
method takes a single argument,
validateEmployeeXML() method is as follows:
public static function validateEmployeeXML(employee:XML):void
{
// checks for the integrity of items in the XML
if (employee.costCenter.length() < 1)
{
throw new FatalError(9000);
}
if (employee.costCenter.length() > 1)
{
throw new WarningError(9001);
}
if (employee.ssn.length() != 1)
{
throw new FatalError(9002);
}
}
employee, which is the XML packet that you want to validate. The
To be validated, an employee must belong to one (and only one) cost center. If the employee doesn’t belong to any cost
centers, the method throws a FatalError, which bubbles up to the
validateData() method in the main application
file. If the employee belongs to more than one cost center, a WarningError is thrown. The final check in the XML
validator is that the user has exactly one social security number defined (the
not exactly one
ssn node, a FatalError error is thrown.
ssn node in the XML packet). If there is
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
You can add additional checks to the validateEmployeeXML() method—for example, to ensure that the ssn node
contains a valid number, or that the employee has at least one phone number and e-mail address defined, and that both
values are valid. You can also modify the XML so that each employee has a unique ID and specifies the ID of their
manager.
Defining the ApplicationError class
Flash Player 9 and later, Adobe AIR 1.0 and later
The ApplicationError class serves as the base class for both the FatalError and WarningError classes. The
ApplicationError class extends the Error class, and defines its own custom methods and properties, including defining
an error ID, severity, and an XML object that contains the custom error codes and messages. This class also defines
two static constants that are used to define the severity of each error type.
The ApplicationError class’s constructor method is as follows:
public function ApplicationError()
{
messages =
<errors>
<error code="9000">
<![CDATA[Employee must be assigned to a cost center.]]>
</error>
<error code="9001">
<![CDATA[Employee must be assigned to only one cost center.]]>
</error>
<error code="9002">
<![CDATA[Employee must have one and only one SSN.]]>
</error>
<error code="9999">
<![CDATA[The application has been stopped.]]>
</error>
</errors>;
}
73
Each error node in the XML object contains a unique numeric code and an error message. Error messages can be easily
looked up by their error code using E4X, as seen in the following
public function getMessageText(id:int):String
{
var message:XMLList = messages.error.(@code == id);
return message[0].text();
}
getMessageText() method:
The getMessageText() method takes a single integer argument, id, and returns a string. The id argument is the error
code for the error to look up. For example, passing an
id of 9001 retrieves the error saying that employees must be
assigned to only one cost center. If more than one error has the same error code, ActionScript returns the error
message only for the first result found (
message[0] in the returned XMLList object).
The next method in this class, getTitle(), doesn’t take any parameters and returns a string value that contains the
error ID for this specific error. This value is used to help you easily identify the exact error that occurred during
validation of the XML packet. The following excerpt shows the
public function getTitle():String
{
return "Error #" + id;
}
getTitle() method:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
The final method in the ApplicationError class is toString(). This method overrides the function defined in the
Error class so that you can customize the presentation of the error message. The method returns a string that identifies
the specific error number and message that occurred.
public override function toString():String
{
return "[APPLICATION ERROR #" + id + "] " + message;
}
Defining the FatalError class
Flash Player 9 and later, Adobe AIR 1.0 and later
The FatalError class extends the custom ApplicationError class and defines three methods: the FatalError constructor,
getTitle(), and toString(). The first method, the FatalError constructor, takes a single integer argument,
errorID, and sets the error’s severity using the static constant values defined in the ApplicationError class, and gets
the specific error’s error message by calling the
FatalError constructor is as follows:
public function FatalError(errorID:int)
{
id = errorID;
severity = ApplicationError.FATAL;
message = getMessageText(errorID);
}
getMessageText() method in the ApplicationError class. The
74
The next method in the FatalError class, getTitle(), overrides the getTitle() method defined earlier in the
ApplicationError class, and appends the text “-- FATAL” in the title to inform the user that a fatal error has occurred.
getTitle() method is as follows:
The
public override function getTitle():String
{
return "Error #" + id + " -- FATAL";
}
The final method in this class, toString(), overrides the toString() method defined in the ApplicationError class.
toString() method is
The
public override function toString():String
{
return "[FATAL ERROR #" + id + "] " + message;
}
Defining the WarningError class
Flash Player 9 and later, Adobe AIR 1.0 and later
The WarningError class extends the ApplicationError class and is nearly identical to the FatalError class, except for a
couple minor string changes and sets the error severity to ApplicationError.WARNING instead of
ApplicationError.FATAL, as seen in the following code:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Handling errors
public function WarningError(errorID:int)
{
id = errorID;
severity = ApplicationError.WARNING;
message = super.getMessageText(errorID);
}
75
Last updated 3/21/2011
Chapter 5: Using regular expressions
Flash Player 9 and later, Adobe AIR 1.0 and later
A regular expression describes a pattern that is used to find and manipulate matching text in strings. Regular
expressions resemble strings, but they can include special codes to describe patterns and repetition. For example, the
following regular expression matches a string that starts with the character A followed by one or more sequential digits:
/A\d+/
The following topics describe the basic syntax for constructing regular expressions. However, regular expressions can
have many complexities and nuances. You can find detailed resources on regular expressions on the web and in
bookstores. Keep in mind that different programming environments implement regular expressions in different ways.
ActionScript 3.0 implements regular expressions as defined in the ECMAScript edition 3 language specification
(ECMA-262).
More Help topics
RegExp
76
Basics of regular expressions
Flash Player 9 and later, Adobe AIR 1.0 and later
A regular expression describes a pattern of characters. Regular expressions are typically used to verify that a text value
conforms to a particular pattern (such as verifying that a user-entered phone number has the proper number of digits)
or to replace portions of a text value that matches a particular pattern.
Regular expressions can be simple. For example, suppose you wanted to confirm that a particular string matches
“ABC,” or wanted to replace every occurrence of “ABC” in a string with some other text. In that case, you could use
the following regular expression, which defines the pattern consisting of the letters A, B, and C in sequence:
/ABC/
Note that the regular expression literal is delineated with the forward slash (/) character.
Regular expression patterns can also be complex, and sometimes cryptic in appearance, such as the following
expression to match a valid e-mail address:
Most commonly you will use regular expressions to search for patterns in strings and to replace characters. In those
cases, you will create a regular expression object and use it as a parameter for one of several String class methods. The
following methods of the String class take regular expressions as parameters:
split(). For more information on these methods, see “Finding patterns in strings and replacing substrings” on
page 16.
The RegExp class includes the following methods: test() and exec(). For more information, see “Methods for using
regular expressions with strings” on page 90.
match(), replace(), search(), and
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
Important concepts and terms
The following reference list contains important terms that are relevant to this feature:
Escape character A character indicating that the character that follows should be treated as a metacharacter rather
than a literal character. In regular expression syntax, the backslash character (\) is the escape character, so a backslash
followed by another character is a special code rather than just the character itself.
Flag A character that specifies some option about how the regular expression pattern should be used, such as whether
to distinguish between uppercase and lowercase characters.
Metacharacter A character that has special meaning in a regular expression pattern, as opposed to literally
representing that character in the pattern.
Quantifier A character (or several characters) indicating how many times a part of the pattern should repeat. For
example, a quantifier would be used to designate that a United States postal code should contain five or nine numbers.
Regular expression A program statement defining a pattern of characters that can be used to confirm whether other
strings match that pattern or to replace portions of a string.
Regular expression syntax
77
Flash Player 9 and later, Adobe AIR 1.0 and later
This section describes all of the elements of ActionScript regular expression syntax. As you’ll see, regular expressions
can have many complexities and nuances. You can find detailed resources on regular expressions on the web and in
bookstores. Keep in mind that different programming environments implement regular expressions in different ways.
ActionScript 3.0 implements regular expressions as defined in the ECMAScript edition 3 language specification
(ECMA-262).
Generally, you use regular expressions that match more complicated patterns than a simple string of characters. For
example, the following regular expression defines the pattern consisting of the letters A, B, and C in sequence followed
by any digit:
/ABC\d/
The \d code represents “any digit.” The backslash (\) character is called the escape character, and combined with the
character that follows it (in this case the letter d), it has special meaning in the regular expression.
The following regular expression defines the pattern of the letters ABC followed by any number of digits (note the
asterisk):
/ABC\d*/
The asterisk character (*) is a metacharacter. A metacharacter is a character that has special meaning in regular
expressions. The asterisk is a specific type of metacharacter called a quantifier, which is used to quantify the amount
of repetition of a character or group of characters. For more information, see
“Quantifiers” on page 82.
In addition to its pattern, a regular expression can contain flags, which specify how the regular expression is to be
matched. For example, the following regular expression uses the
i flag, which specifies that the regular expression
ignores case sensitivity in matching strings:
/ABC\d*/i
For more information, see “Flags and properties” on page 87.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
You can use regular expressions with the following methods of the String class: match(), replace(), and search().
For more information on these methods, see
“Finding patterns in strings and replacing substrings” on page 16.
Creating an instance of a regular expression
Flash Player 9 and later, Adobe AIR 1.0 and later
There are two ways to create a regular expression instance. One way uses forward slash characters (/) to delineate the
regular expression; the other uses the
var pattern1:RegExp = /bob/i;
var pattern2:RegExp = new RegExp("bob", "i");
Forward slashes delineate a regular expression literal in the same way as quotation marks delineate a string literal. The
part of the regular expression within the forward slashes defines the pattern. The regular expression can also include
flags after the final delineating slash. These flags are considered to be part of the regular expression, but they are
separate from its pattern.
When using the new constructor, you use two strings to define the regular expression. The first string defines the
pattern, and the second string defines the flags, as in the following example:
var pattern2:RegExp = new RegExp("bob", "i");
new constructor. For example, the following regular expressions are equivalent:
78
When including a forward slash within a regular expression that is defined by using the forward slash delineators, you
must precede the forward slash with the backslash (
matches the pattern
var pattern:RegExp = /1\/2/;
1/2:
\) escape character. For example, the following regular expression
To include quotation marks within a regular expression that is defined with the new constructor, you must add
backslash (
example, the following regular expressions match the pattern
var pattern1:RegExp = new RegExp("eat at \"joe's\"", "");
var pattern2:RegExp = new RegExp('eat at "joe\'s"', "");
\) escape character before the quotation marks (just as you would when defining any String literal). For
eat at "joe's":
Do not use the backslash escape character with quotation marks in regular expressions that are defined by using the
forward slash delineators. Similarly, do not use the escape character with forward slashes in regular expressions that
are defined with the
"joe's":
var pattern1:RegExp = /1\/2 "joe's"/;
var pattern2:RegExp = new RegExp("1/2 \"joe's\"", "");
var pattern3:RegExp = new RegExp('1/2 "joe\'s"', '');
new constructor. The following regular expressions are equivalent, and they define the pattern 1/2
Also, in a regular expression that is defined with the new constructor, to use a metasequence that begins with the
backslash (
var pattern:RegExp = new RegExp("\\d+", ""); // matches one or more digits
\) character, such as \d (which matches any digit), type the backslash character twice:
You must type the backlash character twice in this case, because the first parameter of the RegExp() constructor
method is a string, and in a string literal you must type a backslash character twice to have it recognized as a single
backslash character.
The sections that follow describe syntax for defining regular expression patterns.
For more information on flags, see “Flags and properties” on page 87.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
Characters, metacharacters, and metasequences
Flash Player 9 and later, Adobe AIR 1.0 and later
The simplest regular expression is one that matches a sequence of characters, as in the following example:
var pattern:RegExp = /hello/;
However, the following characters, known as metacharacters, have special meanings in regular expressions:
^ $ \ . * + ? ( ) [ ] { } |
For example, the following regular expression matches the letter A followed by zero or more instances of the letter B
(the asterisk metacharacter indicates this repetition), followed by the letter C:
/AB*C/
To include a metacharacter without its special meaning in a regular expression pattern, you must use the backslash (\)
escape character. For example, the following regular expression matches the letter A followed by the letter B, followed
by an asterisk, followed by the letter C:
var pattern:RegExp = /AB\*C/;
A metasequence, like a metacharacter, has special meaning in a regular expression. A metasequence is made up of more
than one character. The following sections provide details on using metacharacters and metasequences.
79
About metacharacters
The following table summarizes the metacharacters that you can use in regular expressions:
MetacharacterDescription
^ (caret) Matches at the start of the string. With the m (multiline) flag set, the caret matches the start of a line as
$(dollar sign)Matches at the end of the string. With the m (multiline) flag set, $ matches the position before a newline
\ (backslash)Escapes the special metacharacter meaning of special characters.
. (dot)Matches any single character.
* (star)Matches the previous item repeated zero or more times.
+ (plus)Matches the previous item repeated one or more times.
? (question mark)Matches the previous item repeated zero times or one time.
“Flags and properties” on page 87). Note that when used at the start of a character class, the caret
well (see
indicates negation, not the start of a string. For more information, see “Character classes” on page 81.
\n) character as well. For more information, see “Flags and properties” on page 87.
(
Also, use the backslash character if you want to use a forward slash character in a regular expression literal,
/1\/2/ (to match the character 1, followed by the forward slash character, followed by the character
as in
2).
A dot matches a newline character (\n) only if the s (dotall) flag is set. For more information, see “Flags
and properties” on page 87.
For more information, see “Quantifiers” on page 82.
For more information, see “Quantifiers” on page 82.
For more information, see “Quantifiers” on page 82.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
MetacharacterDescription
( and ) Defines groups within the regular expression. Use groups for the following:
• To confine the scope of the | alternator: /(a|b|c)d/
• To define the scope of a quantifier: /(walla.){1,2}/
• In backreferences. For example, the \1 in the following regular expression matches whatever matched
the first parenthetical group of the pattern:
• /(\w*) is repeated: \1/
For more information, see “Groups” on page 84.
[ and ] Defines a character class, which defines possible matches for a single character:
/[aeiou]/ matches any one of the specified characters.
Within character classes, use the hyphen (-) to designate a range of characters:
/[A-Z0-9]/ matches uppercase A through Z or 0 through 9.
Within character classes, insert a backslash to escape the ] and
- characters:
/[+\-]\d+/ matches either + or - before one or more digits.
Within character classes, other characters, which are normally metacharacters, are treated as normal
characters (not metacharacters), without the need for a backslash:
/[$]/£ matches either $or £.
For more information, see “Character classes” on page 81.
80
| (pipe)Used for alternation, to match either the part on the left side or the part on the right side:
/abc|xyz/ matches either abc or xyz.
About metasequences
Metasequences are sequences of characters that have special meaning in a regular expression pattern. The following
table describes these metasequences:
MetasequenceDescription
{n}
{n,}
and
{n,n}
\bMatches at the position between a word character and a nonword character. If the first or last character in
\BMatches at the position between two word characters. Also matches the position between two nonword
\dMatches a decimal digit.
\DMatches any character other than a digit.
\fMatches a form feed character.
Specifies a numeric quantifier or quantifier range for the previous item:
/A{27}/ matches the character A repeated 27 times.
/A{3,}/ matches the character A repeated 3 or more times.
/A{3,5}/ matches the character A repeated 3 to 5 times.
For more information, see “Quantifiers” on page 82.
the string is a word character, also matches the start or end of the string.
characters.
\nMatches the newline character.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
MetasequenceDescription
\rMatches the return character.
\sMatches any white-space character (a space, tab, newline, or return character).
\SMatches any character other than a white-space character.
\tMatches the tab character.
81
\unnnnMatches the Unicode character with the character code specified by the hexadecimal number nnnn. For
\vMatches a vertical feed character.
\wMatches a word character (AZ–, az–, 0-9, or _). Note that \w does not match non-English characters, such
\WMatches any character other than a word character.
\\xnnMatches the character with the specified ASCII value, as defined by the hexadecimal number nn.
\u263a is the smiley character.
example,
é , ñ , or ç .
as
Character classes
Flash Player 9 and later, Adobe AIR 1.0 and later
You use character classes to specify a list of characters to match one position in the regular expression. You define
character classes with square brackets (
class that matches
/b[aeiou]g/
bag, beg, big, bog, or bug:
Escape sequences in character classes
Most metacharacters and metasequences that normally have special meanings in a regular expression do not have
those same meanings inside a character class. For example, in a regular expression, the asterisk is used for repetition,
but this is not the case when the asterisk appears in a character class. The following character class matches the asterisk
literally, along with any of the other characters listed:
[ and ] ). For example, the following regular expression defines a character
/[abc*123]/
However, the three characters listed in the following table do function as metacharacters, with special meaning, in
character classes:
MetacharacterMeaning in character classes
]Defines the end of the character class.
-Defines a range of characters (see the following section “Ranges of characters in character classes”).
\Defines metasequences and undoes the special meaning of metacharacters.
For any of these characters to be recognized as literal characters (without the special metacharacter meaning), you
must precede the character with the backslash escape character. For example, the following regular expression includes
a character class that matches any one of four symbols (
/[$\\\]\-]/
$, \, ], or -):
In addition to the metacharacters that retain their special meanings, the following metasequences function as
metasequences within character classes:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
MetasequenceMeaning in character classes
\nMatches a newline character.
\rMatches a return character.
\tMatches a tab character.
82
\unnnnMatches the character with the specified Unicode code point value (as defined by the hexadecimal number
\\xnnMatches the character with the specified ASCII value (as defined by the hexadecimal number nn).
nnnn).
Other regular expression metasequences and metacharacters are treated as normal characters within a character class.
Ranges of characters in character classes
Use the hyphen to specify a range of characters, such as A-Z, a-z, or 0-9. These characters must constitute a valid range
in the character set. For example, the following character class matches any one of the characters in the range
a-z or
any digit:
/[a-z0-9]/
You can also use the \\xnn ASCII character code to specify a range by ASCII value. For example, the following
character class matches any character from a set of extended ASCII characters (such as
\\x
é and ê ):
Negated character classes
When you use a caret (^) character at the beginning of a character class, it negates that class—any character not listed
is considered a match. The following character class matches any character except for a lowercase letter (
/[^a-z0-9]/
az–) or a digit:
You must type the caret (^) character at the beginning of a character class to indicate negation. Otherwise, you are
simply adding the caret character to the characters in the character class. For example, the following character class
matches any one of a number of symbol characters, including the caret:
/[!.,#+*%$&^]/
Quantifiers
Flash Player 9 and later, Adobe AIR 1.0 and later
You use quantifiers to specify repetitions of characters or sequences in patterns, as follows:
Quantifier metacharacterDescription
* (star)Matches the previous item repeated zero or more times.
+ (plus)Matches the previous item repeated one or more times.
? (question mark)Matches the previous item repeated zero times or one time.
{n}
{n,}
and
{n,n}
Specifies a numeric quantifier or quantifier range for the previous item:
/A{27}/ matches the character A repeated 27 times.
/A{3,}/ matches the character A repeated 3 or more times.
/A{3,5}/ matches the character A repeated 3 to 5 times.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
You can apply a quantifier to a single character, to a character class, or to a group:
• /a+/ matches the character a repeated one or more times.
• /\d+/ matches one or more digits.
• /[abc]+/ matches a repetition of one or more character, each of which is either a, b, or c.
• /(very, )*/ matches the word very followed by a comma and a space repeated zero or more times.
You can use quantifiers within parenthetical groupings that have quantifiers applied to them. For example, the
following quantifier matches strings such as
/\w+(-\w+)*/
word and word-word-word:
By default, regular expressions perform what is known as greedy matching. Any subpattern in the regular expression
(such as
.*) tries to match as many characters in the string as possible before moving forward to the next part of the
regular expression. For example, consider the following regular expression and string:
var pattern:RegExp = /<p>.*<\/p>/;
str:String = "<p>Paragraph 1</p> <p>Paragraph 2</p>";
The regular expression matches the entire string:
<p>Paragraph 1</p> <p>Paragraph 2</p>
Suppose, however, that you want to match only one <p>...</p> grouping. You can do this with the following:
83
<p>Paragraph 1</p>
Add a question mark (?) after any quantifier to change it to what is known as a lazy quantifier. For example, the
following regular expression, which uses the lazy
characters possible (lazy), followed by
/<p>.*?<\/p>/
</p>:
*? quantifier, matches <p> followed by the minimum number of
Keep in mind the following points about quantifiers:
• The quantifiers {0} and {0,0} do not exclude an item from a match.
• Do not combine multiple quantifiers, as in /abc+*/.
• The dot (.) does not span lines unless the s (dotall) flag is set, even if it is followed by a * quantifier. For example,
consider the following code:
var str:String = "<p>Test\n";
str += "Multiline</p>";
var re:RegExp = /<p>.*<\/p>/;
trace(str.match(re)); // null;
re = /<p>.*<\/p>/s;
trace(str.match(re));
// output: <p>Test
//Multiline</p>
For more information, see “Flags and properties” on page 87.
Alternation
Flash Player 9 and later, Adobe AIR 1.0 and later
Use the | (pipe) character in a regular expression to have the regular expression engine consider alternatives for a
match. For example, the following regular expression matches any one of the words
Last updated 3/21/2011
cat, dog, pig, rat:
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
var pattern:RegExp = /cat|dog|pig|rat/;
You can use parentheses to define groups to restrict the scope of the | alternator. The following regular expression
matches
var pattern:RegExp = /cat(nap|nip)/;
cat followed by nap or nip:
For more information, see “Groups” on page 84.
The following two regular expressions, one using the | alternator, the other using a character class (defined with [ and
] ), are equivalent:
/1|3|5|7|9/
/[13579]/
For more information, see “Character classes” on page 81.
Groups
Flash Player 9 and later, Adobe AIR 1.0 and later
You can specify a group in a regular expression by using parentheses, as follows:
/class-(\d*)/
84
A group is a subsection of a pattern. You can use groups to do the following things:
• Apply a quantifier to more than one character.
• Delineate subpatterns to be applied with alternation (by using the | character).
• Capture substring matches (for example, by using \1 in a regular expression to match a previously matched group,
or by using
$1 similarly in the replace() method of the String class).
The following sections provide details on these uses of groups.
Using groups with quantifiers
If you do not use a group, a quantifier applies to the character or character class that precedes it, as the following shows:
var pattern:RegExp = /ab*/ ;
// matches the character a followed by
// zero or more occurrences of the character b
pattern = /a\d+/;
// matches the character a followed by
// one or more digits
pattern = /a[123]{1,3}/;
// matches the character a followed by
// one to three occurrences of either 1, 2, or 3
However, you can use a group to apply a quantifier to more than one character or character class:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
var pattern:RegExp = /(ab)*/;
// matches zero or more occurrences of the character a
// followed by the character b, such as ababab
pattern = /(a\d)+/;
// matches one or more occurrences of the character a followed by
// a digit, such as a1a5a8a3
pattern = /(spam ){1,3}/;
// matches 1 to 3 occurrences of the word spam followed by a space
For more information on quantifiers, see “Quantifiers” on page 82.
Using groups with the alternator (|) character
You can use groups to define the group of characters to which you want to apply an alternator (|) character, as follows:
var pattern:RegExp = /cat|dog/;
// matches cat or dog
pattern = /ca(t|d)og/;
// matches catog or cadog
85
Using groups to capture substring matches
When you define a standard parenthetical group in a pattern, you can later refer to it in the regular expression. This is
known as a backreference, and these sorts of groups are known as capturing groups. For example, in the following
regular expression, the sequence
var pattern:RegExp = /(\d+)-by-\1/;
// matches the following: 48-by-48
\1 matches whatever substring matched the capturing parenthetical group:
You can specify up to 99 of these backreferences in a regular expression by typing \1, \2, ... , \99.
Similarly, in the replace() method of the String class, you can use $1$99– to insert captured group substring matches
in the replacement string:
var pattern:RegExp = /Hi, (\w+)\./;
var str:String = "Hi, Bob.";
trace(str.replace(pattern, "$1, hello."));
// output: Bob, hello.
Also, if you use capturing groups, the exec() method of the RegExp class and the match() method of the String class
return substrings that match the capturing groups:
var pattern:RegExp = /(\w+)@(\w+).(\w+)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example,com
Using noncapturing groups and lookahead groups
A noncapturing group is one that is used for grouping only; it is not “collected,” and it does not match numbered
backreferences. Use
(?: and ) to define noncapturing groups, as follows:
var pattern = /(?:com|org|net);
For example, note the difference between putting (com|org) in a capturing versus a noncapturing group (the exec()
method lists capturing groups after the complete match):
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
var pattern:RegExp = /(\w+)@(\w+).(com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example,com
//noncapturing:
var pattern:RegExp = /(\w+)@(\w+).(?:com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example
A special type of noncapturing group is the lookahead group, of which there are two types: the positive lookahead group
and the negative lookahead group.
Use (?= and ) to define a positive lookahead group, which specifies that the subpattern in the group must match at the
position. However, the portion of the string that matches the positive lookahead group can match remaining patterns
in the regular expression. For example, because
character
group,
var pattern:RegExp = /sh(?=e)(\w*)/i;
var str:String = "Shelly sells seashells by the seashore";
trace(pattern.exec(str));
// Shelly,elly
e that it matches can be matched by a subsequent part of the regular expression—in this case, the capturing
\w*):
(?=e) is a positive lookahead group in the following code, the
86
Use (?! and ) to define a negative lookahead group that specifies that the subpattern in the group must not match at
the position. For example:
var pattern:RegExp = /sh(?!e)(\w*)/i;
var str:String = "She sells seashells by the seashore";
trace(pattern.exec(str));
// shore,ore
Using named groups
A named group is a type of group in a regular expression that is given a named identifier. Use (?P<name> and ) to
define the named group. For example, the following regular expression includes a named group with the identifier
digits:
named
var pattern = /[a-z]+(?P<digits>\d+)[a-z]+/;
When you use the exec() method, a matching named group is added as a property of the result array:
var myPattern:RegExp = /([a-z]+)(?P<digits>\d+)[a-z]+/;
var str:String = "a123bcd";
var result:Array = myPattern.exec(str);
trace(result.digits); // 123
Here is another example, which uses two named groups, with the identifiers name and dom:
var emailPattern:RegExp =
/(?P<name>(\w|[_.\-])+)@(?P<dom>((\w|-)+))+\.\w{2,4}+/;
var address:String = "bob@example.com";
var result:Array = emailPattern.exec(address);
trace(result.name); // bob
trace(result.dom); // example
Note: Named groups are not part of the ECMAScript language specification. They are an added feature in ActionScript 3.0.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Using regular expressions
Flags and properties
Flash Player 9 and later, Adobe AIR 1.0 and later
The following table lists the five flags that you can set for regular expressions. Each flag can be accessed as a property
of the regular expression object.
FlagPropertyDescription
gglobalMatches more than one match.
87
iignoreCaseCase-insensitive matching. Applies to the A—Z and a—z characters, but not to extended characters
mmultilineWith this flag set, $ and ^ can match the beginning of a line and end of a line, respectively.
sdotallWith this flag set, . (dot) can match the newline character (\n).
xextendedAllows extended regular expressions. You can type spaces in the regular expression, which are ignored
É and é .
such as
as part of the pattern. This lets you type regular expression code more legibly.
Note that these properties are read-only. You can set the flags (g, i, m, s, x) when you set a regular expression variable,
as follows:
var re:RegExp = /abc/gimsx;
However, you cannot directly set the named properties. For instance, the following code results in an error:
var re:RegExp = /abc/;
re.global = true; // This generates an error.
By default, unless you specify them in the regular expression declaration, the flags are not set, and the corresponding
properties are also set to
false.
Additionally, there are two other properties of a regular expression:
• The lastIndex property specifies the index position in the string to use for the next call to the exec() or test()
method of a regular expression.
• The source property specifies the string that defines the pattern portion of the regular expression.
The g (global) flag
When the g (global) flag is not included, a regular expression matches no more than one match. For example, with
g flag not included in the regular expression, the String.match() method returns only one matching substring:
the
var str:String = "she sells seashells by the seashore.";
var pattern:RegExp = /sh\w*/;
trace(str.match(pattern)) // output: she
When the g flag is set, the Sting.match() method returns multiple matches, as follows:
var str:String = "she sells seashells by the seashore.";
var pattern:RegExp = /sh\w*/g;
// The same pattern, but this time the g flag IS set.
trace(str.match(pattern)); // output: she,shells,shore
The i (ignoreCase) flag
By default, regular expression matches are case-sensitive. When you set the i (ignoreCase) flag, case sensitivity is
ignored. For example, the lowercase
s in the regular expression does not match the uppercase letter S, the first
character of the string:
Last updated 3/21/2011
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.