Associative array is used so commonly when I write PHP program, for AS3, I used it when I pass extra data for an Event Listener. This passage is not going to discuss about how to pass parameter for Event Listener but to share how I found that the so-called “associative array” is not simply an array but is an onject, for which for a new AS3 programmer, I haven’t imagine about this.
I used to use associative array as it is quite easy to understand what the structure of the data is. For example, I have a variable called “applicationVar”, then for the following code:
applicationVar['name']=”My application”;
applicationVar['author']=”Gordon”;
applicationVar['version']=”1.0″;
By passing 1 variable, people can get the data in bulk which is the advantage of using array, and also instead of using numeric index, I can use those bracketed terms to get the extra information and the program is more readible.
However for me to do the same thing in AS3, I found it seems not so easy to do so:
One direct way is:
var applicationVar:Array=[{name:"My application",author:"Gordon",version:"1.0"}];
But this is not allow to add further item dynamically.
or to use the push function:
var applicationVar:Array=new Array();
applicationVar.push({name:”My application”,author:”Gordon”,version:”1.0″});
But it result that I need to pass 1 more ‘index’ to that ‘array’:
Alert.show(applicationVar[0]['name']); //My application
That extra “[0]” is so ugly.
And finally I found out that AS3 do not suggest people to use Array to achieve the associative array concept:
Do not use the Array class to create associative arrays (also called hashes), which are data structures that contain named elements instead of numbered elements. To create associative arrays, use the Object class. Although ActionScript permits you to create associative arrays using the Array class, you cannot use any of the Array class methods or properties with associative arrays.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html
The method of Using Object instead Array to achieve the associative array concept is:
var applicationVar:Object = new Object();
applicationVar.name = “My application”;
applicationVar.author = “Gordon”;
applicationVar.version = “1.0″;
for (var item in myArray) {
trace(item); // name,author,version
trace(myArray[item]); // My application, Gordon, 1.0
This is the sharing about how to use associative array in AS3.
}