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

Sov*_*iut 21 arrays flash associative-array key actionscript-3

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

如果缺少密钥,我需要执行其他逻辑.我可以抓住undefined property异常,但我希望这可以成为我的最后手段.

Cot*_*ton 37

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

trace("age" in card);  //  return false 
trace("name" in card);  //  return true
Run Code Online (Sandbox Code Playgroud)

试试这个运算符:"in"

  • 这让我高兴,它非常Pythonic. (8认同)

Bry*_*zak 5

hasOwnPropery是你测试它的一种方式.以此为例:


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"));
Run Code Online (Sandbox Code Playgroud)