Saturday, August 28, 2010

Working with Arrays in AS3: Part 5

Today we will learn how to create an Associative Array.

First of all, what is an Associative Array? It is an Array that has named indexes instead of numeric indexes. In fact, an associative array is just an Object class example.

This is how you normally create an Array:

var myArray:Array = ["one", "two", "three"];

Let's take a look at the line above. We have an array with 3 elements. Their indexes are 0, 1 and 2, so if we want to return "two", we will call myArray[1].

In Associative Arrays, each index has its own name. For example, we'll create an Object (or Associative Array, same thing, as I stated above) named customer, that has information about someone's first name, second name and age. We can do it this way:

var customer:Object = new Object();
customer.firstName = "John"
customer.lastName = "Pumpkin"
customer.age = 23

Or we could create it as an Associative Array:

var customer:Object = {firstName: "John", secondName: "Pumpkin", age: 23};

Quite simple. Usually this way you can save space. Returning an element's value is not too hard either, write the object's name, followed by a dot and the property name.


Or you can return values like you do it with normal Arrays, but instead of the numeric index of an element you need to specify it's property name:


If you want to loop through your properties, you can do it like this:

var myTeam:Object = new Object();
myTeam.member1 = "John"
myTeam.member2 = "Bob"
myTeam.member3 = "Greg"

for (var i:int = 1; i <= 3; i++){
trace("Member " + i + " of my team: " + myTeam["member" + i]);
Thanks for reading!


Working with Arrays in AS3: Part 1
Working with Arrays in AS3: Part 2
Working with Arrays in AS3: Part 3
Working with Arrays in AS3: Part 4
Working with Arrays in AS3: Part 6
Working with Arrays in AS3: Part 7

No comments:

Post a Comment