Monday, March 1, 2010

Associative Array, Dictionary and Object!

Sourced from Adobe Livedocs:

An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value.

Unlike other classes, the Object class is dynamic - meaning arbitrary properties can be added to serve as keys.


The following example creates an associative array named monitorInfo, using an object literal to initialize the array with two key and value pairs:

var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};
trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200

If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array, as follows:

var monitorInfo:Object = new Object();

monitorInfo["aspect ratio"] = "16:10"; // bad form, do not use spaces
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspect ratio"], monitorInfo.colors);
// output: 16:10 16.7 million

The Dictionary class lets you create a dynamic collection of properties, which uses strict equality (===) for key comparison.

var dict:Dictionary = new Dictionary();
dict[key] == "Letters";

Iterating with object keys

You can iterate through the contents of a Dictionary object with either a for..in loop or a for each..in loop. A for..in loop allows you to iterate based on the keys, whereas a for each..in loop allows you to iterate based on the values associated with each key.

for (var key:Object in groupMap)
{
trace(key, groupMap[key]);
}
/* output:
[object Sprite] [object Object]
[object Sprite] [object Object]
[object Sprite] [object Object]
*/

for each (var item:Object in groupMap)
{
trace(item);
}
/* output:
[object Object]
[object Object]
[object Object]
*/

No comments:

Post a Comment