AS3: Dictionary Object

// Arrays use numeric indexes:
var arr:Array = new Array();
arr[0] = "value";
// Generic objects use string indexes:
var obj:Object = new Object();
obj["key"] = "value";
// Dictionary uses object keys:
var dict:Dictionary = new Dictionary();
dict[myObj] = "value";

It’s important to understand that Dictionary uses strict equality to match the object, not the reference, as the key. This means that different references to the same object will act as the same key:

import flash.utils.Dictionary;
var a:Object = new Object();
var b:Object = a; // reference to the same object
var dict:Dictionary = new Dictionary();
dict[a] = "fun!";
trace(dict[b]); // traces 'fun!' because a===b
You can use any type of object as a key, not just generic objects (you could use a Sprite, or an Array, for example). This includes primitives (string, boolean, number, int, uint) which are matched based on value (again, strict equality):

var dict:Dictionary = new Dictionary();
dict["string"] = "joy!";
trace(dict["string"]); // traces "joy" because "string"==="string"
Dictionary objects are enumerable with “for in”, and “for each” loops:

for (var key:Object in dict) {
// iterates through each object key
}
for each (var value:Object in dict) {
// iterates through each value
}
You can also set a Dictionary to use weak references as keys. This is pretty cool, because it means that if you clear all references to an object except those in a weakly referenced dictionary, that object will be available for garbage collection, which in turn will release the reference to its value.

var a:Sprite = new Sprite();
// create a weakly referenced dictionary by passing true as first param:
var dict:Dictionary = new Dictionary(true);
dict[a] = new Object();
a = null; // clear original reference to the Sprite.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值