用一些數據設置一個對象。JavaScript對象/數組訪問問題
var blah = {};
blah._a = {};
blah._a._something = '123';
然後希望嘗試和訪問,我該如何去正確地做到這一點?
var anItem = 'a';
console.log(blah._[anItem]);
console.log(blah._[anItem]._something);
用一些數據設置一個對象。JavaScript對象/數組訪問問題
var blah = {};
blah._a = {};
blah._a._something = '123';
然後希望嘗試和訪問,我該如何去正確地做到這一點?
var anItem = 'a';
console.log(blah._[anItem]);
console.log(blah._[anItem]._something);
的bracket notation應該是這樣的:
var anItem = 'a';
console.log(_glw['_'+anItem]);
console.log(_glw['_'+anItem]._something);
You can test it here(注意,我在演示代替_glw
與blah
以匹配原始對象)。
不知道我明白這個問題,但這裏有一些基礎知識。
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);