Flash Essential

AS3 Guide Arrays

Aug 14th 2008
7 Comments
respond
trackback

Show Navigation || Hide Navigation

Quite simply an array is variable that holds multiple variables. Say we had three user names David, John and Jenny. If we were to store these in normal variables we would have to use three lines of code because basic variables can only contain one value.

var first:String = "David"
var second:String = "John"
var third:String ="Jenny"

With the use of Arrays we can take the above code and put it into one line.

var names:Array = ["David", "John", "Jenny"];

You can also create an array by using the array class shown below;

var namesArray:Array = new Array();

The beauty of arrays is that they allow you to add or remove from them at runtime. Lets look at some methods below;

pop() The pop method removes an item from the end of an array.

push() The push method does the opposite and adds to the array.

first we'll look at the push() method;

var namesArray:Array = new Array();
namesArray.push("David");
namesArray.push("John");
trace(namesArray.toString());

The toString method Returns a string that represents the elements in the specified array.

When we test the movie the output window will read "David, John"

pop() method Example

var namesArray:Array = new Array();
namesArray.push("David");
namesArray.push("John");
trace(namesArray.pop());

The output window reads "John" because the pop method Removes the last element from the array.

There are many more array methods that we'll no doubt come across in the next few chapters of this guide but for now it's best just to grasp the basics.


This post is tagged , , ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



7 Comments

Leave a Reply