Arrays in AS3

by kirupa   |   6 September 2011

  Have questions? Discuss this Flash / AS3 tutorial with others on the forums.

Let's imagine you are jotting down a list on a piece of paper. Let's call the piece of paper groceries. Now, in the paper, you write a numbered list starting with zero with all the items that belong there:

a grocery list 

What you have right now is a real-world example of an array! The piece of paper called "groceries" would be your array. The items that you need to purchase are known as the array values.

In this tutorial, you will learn all about what I like to go grocery shopping for. You may indirectly learn a whole lot more about arrays as well!

Declaring an Array

Before you can use an array, you will need to declare it. There are several ways to declare an array. The most common way is to use the following format:

var groceries:Array = new Array("milk", "eggs", "frosted flakes", "salami", "juice");

You have your declaration on the left where you designate the variable as storing an array, and you have your array constructor on the right where you not only create a new array but also populate it with some initial values.

If you have no values to declare, you can just leave the constructor empty:

var groceries:Array = new Array();

The end result is that you will have an array object called groceries with nothing inside it.

Another way to declare an array is to use the array access operator:

var groceries:Array = ["milk", "eggs", "frosted flakes", "salami", "juice"];

In this approach, notice that you are not explicitly calling the Array constructor. You use the angle brackets "[ and ]" to enclose your array's initial values. If you don't want any values when your object is created, you can just leave the inside of the brackets empty:

var groceries:Array = [];

You can use either the explicit "new Array" or array operator approach to instantiate your array object. The end result is the same. The difference is in how your code looks.

In this tutorial, I will explicitly declare the array using the new keyword and not use the array operator.

Displaying an Array

Since it is always satisfying to see what your code is doing - even if it is just plain text, let's next look at how you will display the contents of your array.

It's dreadfully simple:

var groceries:Array = new Array("milk", "eggs", "frosted flakes", "salami", "juice");

All you need to do is pass in your array object into the trace() function.

When you run your application by pressing Ctrl + Enter, your Output window will show all of the items stored inside your array:

The array values are just shown!

[ all of my array items are shown! ]

You should note that this also works because our array is just simple string values. When you start storing anything more complex, this may not work quite as well.

Accessing Array Values

One of the nice things about arrays is that you not only have easy access to the array, but you also have easy access to the array values...similar to highlighting an item in your grocery list:

highlighting an item

The only thing you need to know is what the procedure is for accessing an individual item.

Inside an arrays, each item is assigned a number starting with zero. In the above example, Milk would be given the value 0, Eggs the value 1, Frosted Flakes the value 2, and so on. The formal term for these numbers is called the index value.

The following is how you would use the index value to access a specific item from my array:


The index value is passed in to you array object using the square brackets. In this example, you are referring to the Eggs value because the index position 1 refers to it. If you passed in a 2, you would return Frosted Flakes. You can keep passing in a index value until you have no more values left.

The range of numbers you can use as your index values is one less than your array's length. The reason is that your index values start with a 0. If your array only has 5 items, trying to display grocery[6] or grocery[5] will result in a message of 'undefined' - remember, an array's index starts at 0. An index value of 5 is actually referring to the 6th item in an array.

Let's go one step further. In most real world scenarios, you will want to programmatically go through your array as opposed to accessing each item individually. You can take what I explained in the previous paragraph and use a for loop to do this:

for (var i:int = 0; i < groceries.length; i++)

Notice the the range of your loop starts at 0 and ends just one before your array's full length (as returned by the length property). This works because, like I mentioned earlier, your array index goes from 0 to one short of the value returned for the array's length!

Adding Items to Your Array

You will commonly find yourself wanting to add items to your array. To add items to your array, you will use the push method:


The push method is called on your array, and you pass in the data you want to add to it. The newly added data will always find itself at the end of the array.

For example, after running the code on our initial array, you will see Cookies added to the end of your groceries array:

adding cookies 

If you want to add data to the beginning of your array, you use the unshift method:


When data is added to the beginning of  your array, the index value for all of the existing items increases to account for the newly inserted data:

bananas are added up front

The reason is that the first item in your array will always have an index value of 0. This means that the space originally occupied by the 0th item needs to push itself and everything below it out to make room for the new data.

Both the push and unshift methods, besides adding the elements to the array when you call them, return the new length of the array as well:

var groceries:Array = new Array("milk", "eggs", "frosted flakes", "salami", "juice");
trace(groceries.push("cookies")); // returns 6

Not sure why that is useful, but keep it under your hat in case you do need it.

Removing Items from the Array

To remove an item from the array, you can use the pop or shift methods. The pop method removes the last item from the array and returns it:

var lastItem:String = groceries.pop();

The shift method does the same thing on the opposite end of the array. Instead of the last item being removed and returned, the shift method removes and returns the first item from the array:

var firstItem:String = groceries.shift();

When an item is removed from the beginning of the array, the index positions of all remaining elements is decremented by 1 to fill in the gap:

item removed from the top

Note that, when you are adding items to your array using unshift or push, the returned value from that method call is the new length of your array. When you are removing items using shift and pop, the value returned by the method call is the removed item itself!

Finding Items in the Array

To find items inside your array, you have two built-in methods called indexOf and lastIndexOf. These methods work by scanning your array and returning the index position of the matching element.

The indexOf method returns the first occurence of the item you are searching for:

var groceries:Array = new Array("milk", "eggs", "frosted flakes", "salami", "juice");
var resultIndex = groceries.indexOf("eggs",0);
trace(resultIndex); // 1

Notice that the resultIndex variable stores the result of calling indexOf on our groceries array. To use indexOf, I pass in the element I am looking for along with the index position to start from:


The value returned by indexOf in this case will be 1.

The lastIndexOf method is similar to indexOf in how you use it, but it differs a bit on what it returns when an element is found. Where indexOf finds the first occurrence of the element you are searching for, lastIndexOf finds the last occurence of the element you are searching for and returns that element's index position.

When you search for an element that does not exist in your array, both indexOf and lastIndexOf return a value of -1.

Merging Arrays

The last thing we are going to do is look at how to create a new array that is made up of two separate arrays. Let's say you have two arrays called good and bad:

var good:Array = new Array("Mario", "Luigi", "Kirby", "Yoshi");
var bad:Array = new Array("Bowser", "Koopa Troopa", "Goomba");

To combine both of these arrays into one array, use the concat method on the array you want to make bigger and pass the array you want to merge into it as the argument. What will get returned is a new array whose contents are both good and bad:

var goodAndBad:Array = good.concat(bad);

In this example, because the concat method returns a new array, I create a new Array object called goodAndBad to store the results of our concatenation operation. The order of the elements inside goodAndBad is good first and bad second.


That is almost all there is to know about arrays...well, at least the things you will use them for most frequently. At the very least, you will have learned how to use them to create a grocery list!

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!


Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )


blog comments powered by Disqus


No spam. No fluff. Just awesome content sent straight to your inbox!

Awesome and high-performance web hosting!
new books - yay!!!