2010-10-22 6 views
0

Définissez un objet avec des données.JavaScript Object/Array access question

var blah = {}; 
blah._a = {}; 
blah._a._something = '123'; 

Alors souhaitez essayer et accéder, comment ferais-je correctement?

var anItem = 'a'; 
console.log(blah._[anItem]); 
console.log(blah._[anItem]._something); 

Répondre

6

Le bracket notation devrait ressembler à ceci:

var anItem = 'a'; 
console.log(_glw['_'+anItem]); 
console.log(_glw['_'+anItem]._something); 

You can test it here (note que je l'ai remplacé _glw avec blah dans la démo pour correspondre à l'objet d'origine).

0

Je ne suis pas certain de comprendre la question, mais voici quelques notions de base.

var foo = {}; 

// These two statements do the same thing 
foo.bar = 'a'; 
foo['bar'] = 'a'; 

// So if you need to dynamically access a property 
var property = 'bar'; 
console.log(foo[property]); 
0
var obj = {}; 
obj.anotherObj = {}; 
obj.anotherObj._property = 1; 
var item = '_property'; 
// the following lines produces the same output 
console.log(obj.anotherObj[item]); 
console.log(obj.anotherObj['_property']); 
console.log(obj.anotherObj._property);