Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

Creating arrays

Arrays are objects. As such, they must be instantiated and assigned to reference variables. Then you use the
reference variable and dot syntax to access an array's properties, methods, and elements. The following code
instantiates an empty array:
var myArray:Array = new Array();
All ActionScript arrays have a length property. That length property corresponds to the number of elements
stored in the array at any given time. !xecuting the code below will show that the array currently has "
elements.
var myArray:Array = new Array();
trace(myArray.length); //0
#nce in a while you will $now the number of elements needed for an array before you create it. %or example,
if you were going to create an array to hold every day of the wee$, you would $now that the array only needs
to hold seven elements. &ou would instantiate an array, passing it an integer to specify the number of elements.
var days:Array = new Array( 7 );
trace(days.length); //7
The code above creates an array with seven places to be defined in the future. 't can be helpful to thin$ of an
array as having a number of slots (or indexes) that hold each piece of data. So, an array of seven items could be
visuali*ed as:
Although data is usually added to arrays after they are created, it is possible to instantiate an array with initial
elements.
var days:Array = new Array("Sun", "Mn", "!ue", ""ed", "!hu", "#r$",
"Sat");
trace( days.length ); //7
'f you only provide one value, and the value is a number, it is interpreted as a length.
%inally, it is possible to instantiate an array by assigning it a literal value using a special shortcut syntax. 'n
ActionScript s+uare brac$ets % & are often associated with arrays.
var days:Array = %"Sun", "Mn", "!ue", ""ed", "!hu", "#r$", "Sat"&;
trace( days.length ); //7
&ou can create an empty array in the following way:
var elements:Array = %&;
,egardless of which way you create or populate the array, you will end up with an identical data structure
containing your values.
Manipulating data in arrays
-ata can be added and removed from ActionScript arrays at runtime. &ou can replace existing array
elements or shrin$ or grow the array as needed. There are a number of methods available in the Array class to
manipulate data in an array, but only the most commonly used methods will be discussed here.
push() and pop() methods
The first method is the 'ush() method of the Array class. The 'ush() method adds one or more new
elements to the end of an array. The method returns the new length of the array after the new item(s) have been
added.
var letters:Array = new Array()
letters.'ush( "(" );
letters.'ush( ")", "*", "#" );
var lettersArray+ength:u$nt = letters.'ush( "," );
trace(lettersArray+ength); //-
trace(letters.length); //-
'tems can be removed from the end of an array with the ''() method. The ''() method removes one
element from the end of an array and returns it. .oo$ at the following example:
var letters:Array = new Array();
letters.'ush( "(" );
letters.'ush( ")" );
var letter:Str$ng = letters.''();
trace(letter); //)
letters.'ush( "*" );
trace(letters); //(, *
%or those of you familiar with a Stac$ data structure, the 'ush() and ''() methods provide an easy way to
implement it using an array in ActionScript .
Index
/hile adding data with 'ush() and removing it with ''() is an effective way to manipulate the end of an
array, arrays are most commonly manipulated and accessed via index. 'n ActionScript , an array's index
begins at ", meaning the first element of the array is the "th element.
'ndividual values of the array are accessed by using the name of the array, followed by s+uare brac$ets and the
index you wish to retrieve. %or example:
var days:Array = %"Sun", "Mn", "!ue", ""ed", "!hu", "#r$", "Sat"&;
trace(days%.&); //Mn
&ou can thin$ about the array in the code above as loo$ing li$e this:
&ou can also use this same techni+ue to modify the contents of an Array. %or example, you could modify the
string 'Thu' to say '0i1.
var days:Array = %"Sun", "Mn", "!ue", ""ed", "!hu", "#r$", "Sat"&;
days%/& = "0$";
2ecause array indexes are "3based, the last element of the array is always one less than the length. That means
if you have an array of length 4, then the last element of the array is at index 5.
&ou can also use the index to populate data, just as you did with the 'ush() method.
var days:Array = new Array();
days% 0 & = "Sun";
days% . & = "Mn";
shift() unshift() and splice() methods
!lements can also be removed from the beginning of an array with the sh$1t() method. 2y
using sh$1t(), you can use an array as a +ueue. The sh$1t() method removes the element from the first
indexed location and returns it. The remaining elements are moved from their original index location $ to $2.
var 3ueueArray:Array = new Array("ne", "tw", "three", "1ur");
var was4nArray:Str$ng = 3ueueArray.sh$1t();
trace(was4nArray); //ne
trace(3ueueArray); //tw, three, 1ur
&ou can also add elements to the beginning of an array using the unsh$1t(5args) method. The remaining
elements are moved from their original index location of $ to $6.
var array!7nsh$1t:Array = new Array("three", "1ur");
array!7nsh$1t.unsh$1t("tw");
trace(array!7nsh$1t); // tw, three, 1ur
array!7nsh$1t.unsh$1t("8er", "ne");
trace(array!7nsh$1t); //8er, ne, tw, three, 1ur
%inally, the s'l$ce() method allows you to insert data into or remove data from an array at someplace other
than the first or last index locations. /hen using s'l$ce() to add data, elements are moved within the array
to ma$e room for the inserted data. /hen using s'l$ce() to remove data, elements are moved to fill in the
empty space left after removal. /hen you call the s'l$ce() method, you specify three arguments:
the index location to insert data into
how many (if any) elements to the right of the insertion index should be deleted
data to be inserted (optional)
var s'l$ceArray:Array = %"d", "re", "1a", "1a", "s", "la", "t$", "d"&;
s'l$ceArray.s'l$ce(9, 0, "m$");
trace(s'l$ceArray); // d, re, m$, 1a, 1a, s, la, t$, d
s'l$ceArray.s'l$ce(/, .);
trace(s'l$ceArray); // d, re, m$, 1a, s, la, t$, d
Sorting arrays
&ou can sort the data in an array. 2y default the srt() method is ascending (a3*), case sensitive (6 comes
before a), and treats all data as strings. Treating all data as strings means that numerical data will be incorrectly
sorted78"" will come before 9.
&ou can pass the sort method arguments to affect how it sorts.
Array.(AS*4:S*:S4!4;*
Array.)*S(*:)4:,
Array.7:4<7*S=>! 2 thrws a 1alse $1 tw elements are $dent$cal
Array.>*!7>:4:)*?*)A>>A@
Array.:7M*>4(
.oo$ at how array data is sorted in the examples below.
var str$ngArray!Srt:Array = new Array("a''le", "AeBra", "=range",
"ras'Berry", "BlueBerry");
str$ngArray.srt();
trace(str$ngArray!Srt); // =range, AeBra, a''le, BlueBerry, ras'Berry
str$ngArray!Srt.srt(Array.)*S(*:)4:,);
trace(str$ngArray!Srt); // ras'Berry, BlueBerry, a''le, AeBra, =range
str$ngArray!Srt.srt(Array.(AS*4:S*:S4!4;*);
trace(str$ngArray!Srt); //a''le, BlueBerry, =range, ras'Berry, AeBra
var numBerArray:Array = %/, -C, .00, .9, DE&;
numBerArray.srt();
trace(numBerArray); //.00, .9, DE, /, -C
numBerArray.srt(Array.:7M*>4();
trace(numBerArray); ///, .9, DE, -C, .00
%or more advanced sorting or sorting of complex arrays you can either write a function to help
the srt() method or use the srt=n() method.
Homogeneous, heterogeneous and sparse
So far all of the arrays you have seen in this article have been homogenous in that they have contained the
same type of data in every element of the Array. This is fairly common: however, it is not a re+uirement of
ActionScript arrays. 't is perfectly legal to add elements of varied types to an array. The code below creates a
heterogeneous array.
var elements:Array = %"0ell", ..9D, new )ate()&;
;p to this point, the arrays in this article can be referred to as dense arrays. This means that every element has
some form of value present. ActionScript also supports sparse arrays. Sparse arrays have missing elements.
The code below creates a sparse array, as illustrated by the graphic that follows it.
var elements:Array = new Array();
elements% 0 & = "A";
elements% . & = "F";
elements% D & = "(";
elements% / & = ")";
elements% G & = "*";
<ote that there are elements at indexes ",8,,9 and 5. The other positions do not exist in this array. 'f you were
to execute the following line of code on this array:
trace(elements% 9 &); //unde1$ned
you would receive an unde1$ned as your output. Sparse arrays can be very convenient. 0owever, it is
important to note that sparse arrays are significantly slower at runtime. They lac$ the significant optimi*ation
that the %lash =layer can provide to regular arrays which are in a simple fixed order.
Also note that this is different than an array with null values:
var elements:Array = new Array();
elements% 0 & = "A";
elements% . & = "F";
elements% 9 & = null;
elements% D & = "(";
elements% / & = ")";
elements% - & = null;
elements% G & = "*";
/hen you insert null into indexes > and ? you are creating an array with all 4 positions defined. Two of those
'slots' simply contain a null value. An array with null values is a dense array, not a sparse one.
'f you have a sparse array (at least one missing index) and you later fill in each of those missing indexes, %lash
=layer will begin to treat it as a dense array and the performance will improve.
Multidimensional arrays
&ou can add any type of object into an ActionScript array, including more arrays. The following code creates
a new Array, and for each element, adds a new Array. 'n this example the %& syntax is used to create new
Arrays.
var elements:Array = %&;
elements% 0 & = % "A", "F", "(" &;
elements% . & = % ")", "*", "#" &;
elements% D & = % ",", "0", "4" &;
trace( elements% 0 &% 0 & ); //A
As you can see, the resultant memory structure can be thought of more li$e a two3dimensional table and
elements are accessed using two sets of s+uare brac$ets.
trace( elements% 0 &% 0 & ); //A
't is possible to nest arrays inside each of these array elements, ma$ing three3dimensional (or more) arrays.
That practice isn't used very often: however, it is useful to $now the capabilities of the language for the times
when it might be useful.
Looping over arrays
;sing loops with arrays is one of the most common practices in programming. The iteration variable in
a 1r loop can serve as the index for an array, ma$ing it easy to iterate through every element in the array. 'n
the code below, the loop will cause the element at each index to be traced.
var mus$cArray:Array = new Array("d", "re", "m$", "1a", "s");
1r (var $:$nt = 0; $Hmus$cArray.length; $66) I
trace(mus$cArray %$&);
J
//ut'ut
d
re
m$
1a
s
The example below demonstrates that you can use a loop to alter each element in an array.
var numBerArray:Array = %-, .0, .-, 90, 9-&;
trace(numBerArray);
1r (var K:$nt = 0; KH numBerArray.length; K66)I
numBerArray %K&6=9;
J
trace(numBerArray);
//ut'ut 1 1$rst trace()
-
.0
.-
90
9-
//ut'ut 1 secnd trace()
7
.9
.7
99
97
&ou can also iterate through the elements of an array and search for a given value. The function below shows
how you can move through an array element by element and chec$ its value. 'f the function finds the value, it
returns the index of the element in the array. 'f it fails to find the value, it returns a 38.
Dragging and Dropping
Welcome to another one of Foundation Flash's free Flash and ActionScript tutorials. In this tutorial you are going to learn about how to set up
MovieClips as being draggable by the mouse. A full copy of the source code we are using today is available though there isn't much. !his is
what we will be ma"ing#
It's good to start off with a new pro$ect but even if you don't ma"e sure you call the .as file %rag%rop.as and saving it in the same place as
an .fla. Set the document class to &%rag%rop& on the .fla.
'ow some preparation wor" in the .fla. Bump up the frame rate or it will loo" awful guaranteed. () should do it. Create a graphic for what
needs to be dragged*dropped convert it to a symbol and give it an instance name of 'dragme'. +Save and, move on to the .as. !he first
four lines are as follow#
'acLage I
$m'rt 1lash.d$s'lay.Mv$e(l$';
$m'rt 1lash.events.Muse*vent;
'uBl$c class )rag)r' eMtends Mv$e(l$' I
'uBl$c 1unct$n )rag)r'() I
We've loo"ed at everything there before I thin". !he only import thing to not is that we will be using MouseEvent rather than the
usual Event. So we're in our constructor function and we need to thin" about the event listeners we need to add# one for pic"ing up
+mouse down as were clic"ing the button down, and one for putting down +mouse upas we let go,. We will apply these to the thing these to
'dragme' the thing we want dragged and dropped#
dragme.add*vent+$stener(Muse*vent.M=7S*N)=":, muse)wn0andler);
dragme.add*vent+$stener(Muse*vent.M=7S*N7O, muse7'0andler);
J
-"ay we've got out two listeners now for the functions themselves. For these you're going to need to "now about two functions start%rag+,
and stop%rag+, which loo" li"e this#
BKect.start)rag(%'t$nal lcL(enter, 't$nal Bunds&); BKect.st')rag();
As you can see you can't pass any parameters to stop%rag+, but with start%rag+, you can set the ob$ect to have its center at the mouse
pointer regardless of where on the ob$ect the user clic"ed and the bounds where it can be dragged. We won't be using those optional
parameters today. Instead we will combining these simple functions withevt.target which is the ob$ect which had the event done to it i.e.
dragme. .sing evt.target $ust ma"es the functions more universal#
'r$vate 1unct$n muse)wn0andler(evt:Muse*vent):v$d I
var BK = evt.target;
BK.start)rag();
J
'r$vate 1unct$n muse7'0andler(evt:Muse*vent):v$d I
var BK = evt.target;
BK.st')rag();
J
J
J

You might also like