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
fonte
2015-12-06 19:41:31
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
(Questo non funziona) – Lego
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? –