質問

のActionScript 3では、連想配列(辞書)が特定のキーを持っているかどうかを決定する任意の便利な方法はありますか?

私は、キーが欠落している場合、追加のロジックを実行する必要があります。私はundefined property例外をキャッチすることができますが、私はそれが私の最後の可能願っています。

役に立ちましたか?

解決

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

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

この演算子を試してみてください

他のヒント

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

最も簡単な方法は、最も簡単かもしれ

// 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を人気解決策のようですが、それはそれは文字列のみで扱うと呼び出すことが高価なことができることを指摘する価値がある。

あなたの辞書hasOwnPropertyをキーとしてオブジェクトを使用している場合は動作しません。

より信頼性とパフォーマンスの高いソリューションは、未定義を確認するために厳格な平等を使用することです。

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

空のすなわちになりますNULL値が、有効なキーとそれ以外のエントリを厳密な等価を使用してください。

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

そして実際に、あまりにも正常に動作する必要がありますinを使用して述べてきたように、

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

これを試してください:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top