开发者

JavaScript Object/Array access question

开发者 https://www.devze.com 2023-01-21 18:55 出处:网络
Set an object, with some data. var blah = {}; blah._a = {}; blah._a._some开发者_运维知识库thing = \'123\';

Set an object, with some data.

var blah = {};
blah._a = {};
blah._a._some开发者_运维知识库thing = '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);
0

精彩评论

暂无评论...
验证码 换一张
取 消