Intro to Arrays

scaredyCat

Don’t let ARRAYS frighten you!

If you’re new to ARRAYS in ActionScript 3.0 you might feel a little       intimidated. Don’t be! Start with these basic concepts and you’ll be off and     running in no time…

What is an ARRAY?
First note that an array in ActionScript is an object. If you don’t know what an object is yet, don’t worry, you’ll understand soon. Arrays are lists of data, capable of storing multiple items.

Why do we use ARRAYS?
Arrays make it simple to retrieve items and process them in a logical order.

Creating ARRAYS:
There are various methods to create an array.  You can use the keyword new with the class name:

var  myArray:Array = new Array(“Pumpkin”, “Ghost”, “Witch”);

A shorter technique uses the square brackets [ ] to instantiate an ARRAY:

var  myArray:Array = [“Pumpkin”,”Ghost”,”Witch”];

To access elements in an ARRAY:
First you must know that the index (position) of an array starts at 0 not 1! Simply use the square brackets [ ] to retrieve it. Using the same example from above:

trace(myArray[2];
Output equals: “Witch”.

Use .length when you need to retrieve the number of items in an array:

var  myArray:Array = [“Pumpkin”,”Ghost”,”Witch”];
trace(myArray.length);
Output is: 3

Adding items to an ARRAY:
The easiest way to add more elements is using square brackets [ ].

myArray[3] = “Spooky”;
trace(myArray);
Output should be: “Pumpkin,Ghost,Witch,Spooky”.

Use push() method to automatically add items to the end of your list.

myArray.push(“Spiderwebs”);
trace(myArray);
Output is: “”Pumpkin,Ghost,Witch,Spooky,Spiderwebs”.

Removing items from ARRAYS:
Use the splice() method to remove one or more items from an array. You must specify the starting index and the number of items(deleteCount). If you don’t include the deleteCount, it will delete everything after the index. To get rid of “Ghost”:

var  myArray:Array = [“Pumpkin”,”Ghost”,”Witch”,”Spooky”,”Spiderwebs”];
myArray.splice(1,1);
trace(myArray);
Output is: “Pumpkin,Witch,Spooky,Spiderwebs”.

To get rid of everything after “Pumpkin”:
myArray.splice(1);

Use pop() to remove the last item (handy when you don’t know the last index number).

var  myArray:Array = [“Pumpkin”,”Ghost”,”Witch”,”Spooky”,”Spiderwebs”];
myArray.pop();
trace(myArray);
Output is: “Pumpkin,Ghost,Witch,Spooky”.

I hope you enjoyed my spooky intro to ARRAYS.  Feel free to leave comments or questions.

HAPPY HALLOWEEN!
Follow us on Facebook!

Leave a Reply

Your email address will not be published. Required fields are marked *