在ActionScript 3中,有没有一种方便的方法来确定一个关联数组(字典)是否具有特定的键?
如果缺少键,我需要执行其他逻辑。我可以捕获 undefined property
异常,但我希望这是我的最后一招。
在ActionScript 3中,有没有一种方便的方法来确定一个关联数组(字典)是否具有特定的键?
如果缺少键,我需要执行其他逻辑。我可以捕获 undefined property
异常,但我希望这是我的最后一招。
var card:Object = {name:"Tom"};
trace("age" in card); // return false
trace("name" in card); // return true
尝试使用这个运算符:"in"
hasOwnProperty
是一种测试它的方法。以这个为例:
var dict: Dictionary = new Dictionary();
// this will be false because "foo" doesn't exist
trace(dict.hasOwnProperty("foo"));
// add foo
dict["foo"] = "bar";
// now this will be true because "foo" does exist
trace(dict.hasOwnProperty("foo"));
// creates 2 instances
var obj1:Object = new Object();
var obj2:Object = new Object();
// creates the dictionary
var dict:Dictionary = new Dictionary();
// adding the first object to the dictionary (but not the second one)
dict[obj1] = "added";
// checks whether the keys exist
var test1:Boolean = (dict[obj1] != undefined);
var test2:Boolean = (dict[obj2] != undefined);
// outputs the result
trace(test1,test2);
hasOwnProperty似乎是一种常见的解决方案,但值得注意的是它只适用于字符串,并且调用起来可能会很昂贵。
如果你正在使用对象作为字典中的键,则hasOwnProperty将无法正常工作。
更可靠和高效的解决方案是使用严格相等运算符来检查undefined。
function exists(key:*):Boolean {
return dictionary[key] !== undefined;
}
记得使用严格相等(strict equality)比较,否则具有 null 值但有效键的条目将会看起来为空,例如:
null == undefined // true
null === undefined // false
实际上,正如已经提到的那样,使用in
也应该可以正常工作。
function exists(key:*):Boolean {
return key in dictionary;
}
试试这个:
for (var key in myArray) {
if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
if (! 'key' in obj)
- 您需要使用if (! ('key' in obj))
。 - Richard