2010-10-22 137 views
0

用一些数据设置一个对象。JavaScript对象/数组访问问题

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

然后希望尝试和访问,我该如何去正确地做到这一点?

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

回答

6

bracket notation应该是这样的:

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

You can test it here(注意,我在演示代替_glwblah以匹配原始对象)。

0

不知道我明白这个问题,但这里有一些基础知识。

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