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

21

在ActionScript 3中,有没有一种方便的方法来确定一个关联数组(字典)是否具有特定的键?

如果缺少键,我需要执行其他逻辑。我可以捕获 undefined property 异常,但我希望这是我的最后一招。

5个回答

38
var card:Object = {name:"Tom"};

trace("age" in card);  //  return false 
trace("name" in card);  //  return true

尝试使用这个运算符:"in"


谢谢Cotton,我甚至不知道这个运算符在for-each循环之外还存在。 - BefittingTheorem
8
这让我感到开心,非常符合Pythonic的风格。 - Soviut
1
可能是因为它是一个本地关键字。你总是可以测试多个解决方案,看看哪一个能够产生最佳性能。在那之前,我会选择内置的解决方案。 - Soviut
1
请注意,“in”的优先级非常低 - 例如,这个表达式不会按照我期望的方式工作:if (! 'key' in obj) - 您需要使用 if (! ('key' in obj)) - Richard

5

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

4
最快的方式可能是最简单的:
// 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);

1
但是如果您没有对原始对象的引用,那么这是否有效呢? Cotton的答案似乎更适合这里。 - Mikko Tapionlinna
嘿,在你的问题中,你提到了字典而不是对象或数组,我说得对吗?我还没有尝试在字典实例中使用“in”运算符,应该没问题。让我知道(LMK)。 - Theo.T

2

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;
}

1

试试这个:

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

请记得使用 === 而不是 ==,否则可能会得到错误的结果。 - Jacob Poul Richardt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接