2010-05-02 16 views
27

Sto tentando di leggere una proprietà su una serie di Sprites. Questa proprietà può o non può essere presente su questi oggetti e non può nemmeno essere dichiarata, peggio che essere nulla.Come verificare se esiste una proprietà su un oggetto prima di leggere il suo valore?

Il mio codice è:

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

E così mi mostra Flash:

Error # 1069: proprietà selezionabile non trovato sul flash.display.Sprite e non v'è alcun valore predefinito.

C'è un modo per verificare se esiste una proprietà prima di leggere il suo valore?

Qualcosa di simile:

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

risposta

53

Oggetti in AS3 hanno il metodo hasOwnProperty che prende un argomento di tipo stringa e restituisce true se l'oggetto è che proprietà definita.

if(myObj.hasOwnProperty("someProperty")) 
{ 
    // Do something 
} 
0

provare qualcosa di simile:

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

} 
+4

questo può causare errori se non esiste in primo luogo. vedresti l'errore se stai creando un oggetto dinamicamente come cercare una ["b"] in "var a: Object = {a: '1'}' – Daniel

+0

(Questo non funziona) – Lego

+0

var a; a = a {a: 1}; trace (a ["b"]), restituisce "undefined", ma non genera alcun errore. Quindi, dov'è il problema nell'usare in questo modo? –

17
if ("readable" in child) { 
    ... 
1

L'aggiunta di questo in quanto è una risposta superiore in Google.

Se si sta tentando di verificare se esiste una costante utilizzando una stringa per il nome quindi utilizzare

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

Response to @Vishwas G (non un commento, perché blocchi di codice non sono supportati nei commenti):

Come Daniel ha sottolineato, se l'oggetto "a" nel tuo esempio non esiste in primo luogo, il tuo tentativo di accedere a "b" su "a" causerà un errore. Questo accade nei casi in cui ti aspetti una struttura profonda, come un oggetto JSON che potrebbe, ad esempio, avere il formato "content.social.avatar". Se "social" non esiste, tentare di accedere a "content.social.avatar" causerà un errore.

Ecco un esempio generale-caso di un test di proprietà esistenza profonda struttura in cui l'approccio "indefinito" può causare un errore nel caso in cui il "hasOwnProperty()" approccio non lo fa:

// 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"}}}; 

Ora i test ...

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

Si noti che JavaScript di linguaggio di pari livello di ActionScript non genererebbe un errore nell'esempio test1. Tuttavia, se estendi la gerarchia degli oggetti ancora un livello, ti imbatterai in errori anche in 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