Maps in ActionScript
Maps are an ActionScript’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the new Object() or shorthand {} syntax.
var m:Object = {};
Set key/value pairs using typical name[key] = val syntax.
m["k1"] = 7;
m["k2"] = 13;
Printing a map with, for example, trace will show all of its key/value pairs.
trace("map:", m);
Get a value for a key with name[key].
var v1:int = m["k1"];
trace("v1:", v1);
If the key doesn’t exist, the undefined value of the value type is returned.
var v3:int = m["k3"];
trace("v3:", v3);
The built-in length property can be emulated using a custom function to count the number of key/value pairs.
function mapLength(map:Object):int {
var count:int = 0;
for (var key:String in map) {
count++;
}
return count;
}
trace("len:", mapLength(m));
Deleting a key/value pair in ActionScript can be done using the delete
keyword.
delete m["k2"];
trace("map:", m);
To remove all key/value pairs from a map, use a custom function to iterate and delete all keys.
function clearMap(map:Object):void {
for (var key:String in map) {
delete map[key];
}
}
clearMap(m);
trace("map:", m);
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be achieved using the in
keyword.
var prs:Boolean = "k2" in m;
trace("prs:", prs);
You can also declare and initialize a new map in the same line with this syntax.
var n:Object = {"foo": 1, "bar": 2};
trace("map:", n);
Note that there is no maps
package in ActionScript, but similar functionality can be built using custom functions. Here’s an equivalent to check if two maps are equal:
function mapsEqual(map1:Object, map2:Object):Boolean {
for (var key:String in map1) {
if (map1[key] !== map2[key]) {
return false;
}
}
for (key in map2) {
if (map1[key] !== map2[key]) {
return false;
}
}
return true;
}
var n2:Object = {"foo": 1, "bar": 2};
if (mapsEqual(n, n2)) {
trace("n == n2");
}
Note that maps appear in the form {k:v, k:v} when printed with trace
.
trace("map:", m);
trace("v1:", v1);
trace("v3:", v3);
trace("len:", mapLength(m));
trace("map:", m);
trace("map:", m);
trace("prs:", prs);
trace("map:", n);
trace("n == n2");