简体   繁体   中英

JavaScript Object/Array access question

Set an object, with some data.

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

Then wish to try and access, how would I go about doing this correctly?

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

The bracket notation should look like this:

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

You can test it here (note that I replaced _glw with blah in the demo to match the original object).

Not sure I understand the question, but here are some basics.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM