Skip to content


Associative Arrays

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.

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.

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.

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);

Posted in ActionScript 3.0, Work. Tagged with , .

3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. liz said

    sweet, this is helpful thanks.

  2. Henry Mempin said

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

  3. 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'] + "." );