User Guide
238 Working with Arrays
The following code creates three instances of the Sprite class that serve as keys for the
Dictionary object. Each key is assigned a value of either
GroupA or GroupB. The values can be
of any data type, but in this example both
GroupA and GroupB are instances of the Object
class. Subsequently, you can access the value associated with each key with the property access
(
[]) operator, as shown in the following code:
import flash.display.Sprite;
import flash.utils.Dictionary;
var groupMap:Dictionary = new Dictionary();
// objects to use as keys
var spr1:Sprite = new Sprite();
var spr2:Sprite = new Sprite();
var spr3:Sprite = new Sprite();
// objects to use as values
var groupA:Object = new Object();
var groupB:Object = new Object();
// Create new key-value pairs in dictionary.
groupMap[spr1] = groupA;
groupMap[spr2] = groupB;
groupMap[spr3] = groupB;
if (groupMap[spr1] == groupA)
{
trace("spr1 is in groupA");
}
if (groupMap[spr2] == groupB)
{
trace("spr2 is in groupB");
}
if (groupMap[spr3] == groupB)
{
trace("spr3 is in groupB");
}
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.