web-dev-qa-db-ja.com

値を読み取る前に、オブジェクトにプロパティが存在するかどうかをテストするにはどうすればよいですか?

一連のスプライトのプロパティを読み取ろうとしています。このプロパティは、これらのオブジェクトに存在する場合と存在しない場合があり、nullであるよりも悪い場合は、宣言されない場合もあります。

私のコードは:

if (child["readable"] == true){
    // this Sprite is activated for reading
}

そして、Flashは私に次のことを示しています。

エラー#1069:プロパティ選択可能がflash.display.Spriteに見つからず、デフォルト値がありません。

値を読み取る前にプロパティが存在するかどうかをテストする方法はありますか?

何かのようなもの:

if (child.isProperty("readable") && child["readable"] == true){
    // this Sprite is activated for reading
}
28
Robinicks

AS3のオブジェクトには hasOwnProperty メソッドがあり、文字列引数を取り、オブジェクトにそのプロパティが定義されている場合はtrueを返します。

if(myObj.hasOwnProperty("someProperty"))
{
    // Do something
}
55
Greg B
if ("readable" in child) {
  ...
18
kennytm

これを追加すると、Googleのトップレスポンスです。

名前に文字列を使用して定数が存在するかどうかを確認しようとしている場合は、

if (ClassName["ConstName"] !== undefined) {
    ...
}
1
SystemicPlural

@Vishwas Gへの応答(コードブロックはコメントでサポートされていないため、コメントではありません):

ダニエルが指摘したように、例のオブジェクト「a」がそもそも存在しない場合、「a」の「b」にアクセスしようとするとエラーが発生します。これは、たとえば「content.social.avatar」の形式のJSONオブジェクトなど、深い構造が必要な場合に発生します。 「social」が存在しない場合、「content.social.avatar」にアクセスしようとするとエラーが発生します。

これは、「hasOwnProperty()」アプローチがエラーを引き起こさない場合に「未定義」アプローチがエラーを引き起こす可能性がある深層構造プロパティ存在テストの一般的なケースの例です。

// Missing property "c". This is the "invalid data" case.
var test1:Object = { a:{b:"hello"}};
// Has property "c". This is the "valid data" case.
var test2:Object = { a:{b:{c:"world"}}};

今テスト...

// ** Error ** (Because "b" is a String, not a dynamic
// object, so ActionScript's type checker generates an error.)
trace(test1.a.b.c);  
// Outputs: world
trace(test2.a.b.c);  

// ** Error **. (Because although "b" exists, there's no "c" in "b".)
trace(test1.a && test1.a.b && test1.a.b.c);
// Outputs: world
trace(test2.a && test2.a.b && test2.a.b.c);  

// Outputs: false. (Notice, no error here. Compare with the previous
// misguided existence-test attempt, which generated an error.)
trace(test1.hasOwnProperty("a") && test1.a.hasOwnProperty("b") && test1.a.b.hasOwnProperty("c"));  
// Outputs: true
trace(test2.hasOwnProperty("a") && test2.a.hasOwnProperty("b") && test2.a.b.hasOwnProperty("c")); 

ActionScriptの兄弟言語JavaScriptは、test1の例ではエラーを生成しないことに注意してください。ただし、オブジェクト階層をもう1レベル拡張すると、JavaScriptでもエラーが発生します。

// ** Error (even in JavaScript) ** because "c" doesn't even exist, so
// test1.a.b.c.d becomes an attempt to access a property on undefined,
// which always yields an error.
alert(test1.a.b.c.d)

// JavaScript: Uncaught TypeError: Cannot read property 'd' of undefined
0
colin moock

次のようなものを試してください。

if (child["readable"] != null){

}
0
smartali89