Internet Explorer 6 is not supported.
Upgrade to view this site.

Associative Arrays

Posted on January 17, 2009 at 7:57 pm

An Associative Array can be made in ActionScript 3 by using an Object instead of an Array. You use the Object to make a name/value pair. Name/Value pairs consist of a name and a value and are separated by a colon. The name is what you use to reference the value. When you reference what is in the Associative Array you just write the name as if it was a property on the Object. Here is an example of how to make an Associative Array.

1
2
3
var info:Object = {name:"Tony", occupation:"Bouncer", iq:80};
 
trace("My name is " + info.name + " and I am a " + info.occupation + " with an IQ of " + info.iq + "." );

You could also write it out long-handed and the effect would be the same. Below is the same thing but the names are added as dynamic properties of the newly instantiated Object.

1
2
3
4
5
6
var info:Object = new Object();
info.name = "Tony";
info.occupation = "Bouncer";
info.iq = 80;
 
trace("My name is " + info.name + " and I am a " + info.occupation + " with an IQ of " + info.iq + "." );

They only problem with this is that you lose the length property on this Associative Array. If you try getting the length property it will come up as undefined. I looked this up and found that Senocular actually has a class that fixes this. That class is called¬†AssociativeArray and it can be found here. When I first tried it I got an error at line 32. I didn’t read the class to figure out what was wrong, but I commented out the line throwing the error and it seems to work fine. Here is an example of that class in action.

1
2
3
4
5
6
7
8
var info:AssociativeArray = new AssociativeArray();
 
info.name = "Tony";
info.occupation = "Bouncer";
info.iq = 80;
 
trace("My name is " + info.name + " and I am a " + info.occupation + " with an IQ of " + info.iq + "." );
trace(info.length);
Categories
Tags

3 Comments

liz

sweet, this is helpful thanks.

Posted June 18, 2009 at 4:17 pm
Henry Mempin

Hi, how can i convert the Array into Associated array ( eg, 0,1,2,3,4 into distinctive name like IDNO,FNAME, SECTION, POSITION)

Posted August 9, 2009 at 9:57 am
Robert Abramski

Henry, there is no way to convert really, so use an object instead of an array from the start. You can access it either with the dot syntax or the array syntax. The array syntax below is what you might be used to.

trace("My name is " + info['name'] +
" and I am a " + info['occupation'] +
" with an IQ of " + info['iq'] + "." );
Posted August 10, 2009 at 2:43 pm

Leave a Comment

*Required fields. Email will not be published.