Question

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.

Was it helpful?

Solution

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

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

Try this operator : "in"

OTHER TIPS

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

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

hasOwnProperty seems to be the popular solution, but it's worth pointing out that it only deals in strings and can be expensive to call.

If you're using objects as keys in your Dictionary hasOwnProperty will not work.

The more reliable and performant solution is to use strict equality to check for undefined.

function exists(key:*):Boolean {
    return dictionary[key] !== undefined;
}

Remember to use strict equality otherwise entries with a null value but valid key will look empty i.e.

null == undefined // true
null === undefined // false

And actually, as has been mentioned using in should work fine too

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

Try this:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top