Flash 如何确定关联数组是否有键?

Flash 如何确定关联数组是否有键?,flash,actionscript-3,arrays,associative-array,key,Flash,Actionscript 3,Arrays,Associative Array,Key,在ActionScript3中,是否有任何方便的方法来确定关联数组(字典)是否具有特定的键 如果钥匙丢失,我需要执行额外的逻辑。我可以捕获未定义属性异常,但我希望这是我最后的选择。尝试以下方法: for (var key in myArray) { if (key == myKey) trace(myKey+' found. has value: '+myArray['key']); } 最快的方法可能是最简单的: // creates 2 instances var obj1:Obj

在ActionScript3中,是否有任何方便的方法来确定关联数组(字典)是否具有特定的键

如果钥匙丢失,我需要执行额外的逻辑。我可以捕获
未定义属性
异常,但我希望这是我最后的选择。

尝试以下方法:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}

最快的方法可能是最简单的:

// 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);

试试这个操作符:“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"));

hasOwnProperty似乎是流行的解决方案,但值得指出的是,它只处理字符串,调用起来可能很昂贵

如果将对象用作词典中的键,hasOwnProperty将不起作用

更可靠、更高性能的解决方案是使用严格相等来检查未定义的

function exists(key:*):Boolean {
    return dictionary[key] !== undefined;
}
请记住使用严格相等,否则具有空值但有效密钥的条目将看起来为空,即

null == undefined // true
null === undefined // false
事实上,正如前面提到的,在中使用
也可以很好地工作

function exists(key:*):Boolean {
    return key in dictionary;
}

记住使用===而不是==,我想你可能会以另一种方式得到错误的命中。但是,如果你没有对原始对象的引用,这是否有效?Cottons的答案似乎更适合这里。嘿,在你的问题中,你提到的是字典,而不是对象或数组,对吗?到目前为止,我还没有在Dictionary实例中尝试“in”操作符,应该可以。LMKThanks Cotton,我甚至不知道操作符存在于for-each循环之外。这让我很高兴,它非常像python。可能是因为它是一个本地关键字。您始终可以测试多个解决方案,以查看哪种解决方案产生最佳性能。在此之前,我会使用内置解决方案。请注意,“in”的优先级很低-例如,这并不像我预期的那样起作用:
if(!'key'in obj)
-您需要使用
if(!('key'in obj))
function exists(key:*):Boolean {
    return key in dictionary;
}