views:

2879

answers:

4

In ActionScript 3, is there any convenient way of determining if an associative array (dictionary) has a particular key?

I need to perform additional logic if the key is missing. I could catch the undefined property exception, but I'm hoping that can be my last resort.

+1  A: 

Try this:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
evilpenguin
Remember to use === instead of ==, think you might get a false hit the other way.
Lillemanden
+3  A: 

The quickest way may be the simplest:

// 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);
Theo.T
But does that work if you have no reference to the original object? Cottons answer seems to suit better here.
Mikko Tapionlinna
Hey, in your question you are mentioning Dictionaries and not Objects or Arrays, am I right ? I haven't tried the "in" operator within a Dictionary instance so far, should be ok. LMK
Theo.T
+7  A: 
var card:Object = {name:"Tom"};

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

Try this operator : "in"

Cotton
Thanks Cotton, I never even knew that operator existed outside of a for-each loop.
Brian Heylin
this makes me happy, its very Pythonic.
Soviut
+2  A: 

hasOwnPropery is one way you test for it. Take this for example:


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