说我在javascripts中有这样的东西:
var obj = {
subObj : {}
};
var type = 'subObj';
如何获得obj's
subObj
w / type
?例如,我想做类似的事情:
obj.(type);
答案 0 :(得分:33)
obj[type]
您使用下标符号。
使用点表示法按名称访问属性:
MemberExpression . IdentifierName
CallExpression . IdentifierName
或括号表示法:
MemberExpression [ Expression ]
CallExpression [ Expression ]
答案 1 :(得分:5)
您可以在JavaScript中处理关联数组之类的对象,因此您将能够访问内部对象,如:
var obj = {
subObj : {}
};
var type = "subObj";
var subObj = obj[type];
答案 2 :(得分:2)
如果有人想知道如何(动态地)访问子属性,我找到了一种方法,如果有更简单的方法,请告诉我:
function getPropertyByKeyPath(targetObj, keyPath) {
var keys = keyPath.split('.');
if(keys.length == 0) return undefined;
keys = keys.reverse();
var subObject = targetObj;
while(keys.length) {
var k = keys.pop();
if(!subObject.hasOwnProperty(k)) {
return undefined;
} else {
subObject = subObject[k];
}
}
return subObject;
}
例如:
var o = {result : {info:{ version:1, comment: 'test'}}};
var subObject = getPropertyByKeyPath(o, 'result.info');
console.log(subObject);
会导致:
{version: 1, comment: "test"}
答案 3 :(得分:0)
obj[type]
根本没有任何意义 - 你没有访问TYPES,这些是简单的属性 - 可以通过obj[keyName]
或类似的东西访问它们但是使用type
是非常混乱的,并且是缺乏理解
答案 4 :(得分:-1)
var obj = {
subObj : {}
}
var type = 'subObj';
console.log(typeof obj.subObj); //will print "object"
console.log(obj.subObj); //will print "{}"
//You can add a new propery like this:
obj.subObj.newProperty = 'hello';
console.log(typeof obj.subObj.newProperty); //will print "string"
console.log(obj.subObj.newProperty); //will print "hello"
// you can also add new properties like this
obj.subObj['newProperty'] = 5; // this is very useful if you have to add properties with names that use reserved words or that contain illegal characters.
console.log(typeof obj.subObj.newProperty); //will print "number"
console.log(obj.subObj.newProperty); //will print "5"
//In the case where you're using reserved or illegal words you'l have to do this
obj.subObj['new/Property'] = 'cat'; // this is very useful if you have to add properties with names that use reserved words or that contain illegal characters.
console.log(typeof obj.subObj['new/Property']); //will print "number"
console.log(obj.subObj['new/Property]); //will print "5"
// and add another property in the chain:
obj.subObj['new/PropertyGroup']={
'illegal/name':'value',
acceptableName: 5,
andotherObject:{},
'illegally&Named(object)':{}
}