【发布时间】:2011-12-19 02:56:58
【问题描述】:
假设我在 javascripts 中有这样的东西:
var obj = {
subObj : {}
};
var type = 'subObj';
我怎样才能得到obj's subObj 和type?例如,我想做类似的事情:
obj.(type);
【问题讨论】:
标签: javascript
假设我在 javascripts 中有这样的东西:
var obj = {
subObj : {}
};
var type = 'subObj';
我怎样才能得到obj's subObj 和type?例如,我想做类似的事情:
obj.(type);
【问题讨论】:
标签: javascript
obj[type]
你使用下标符号。
属性通过名称访问,使用点符号:
MemberExpression . IdentifierName
CallExpression . IdentifierName
或括号表示法:
MemberExpression [ Expression ]
CallExpression [ Expression ]
【讨论】:
您可以将对象视为 JavaScript 中的关联数组,因此您可以像这样访问内部对象:
var obj = {
subObj : {}
};
var type = "subObj";
var subObj = obj[type];
【讨论】:
如果有人想知道如何(动态)访问子属性,我已经找到了一种方法,如果有更简单的方法,请告诉我:
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"}
【讨论】:
obj[type]
根本没有任何意义 - 你没有访问类型,这些是简单的属性 - 可以通过 obj[keyName] 或类似的方式访问它们,但使用 type 非常令人困惑,并且肯定是缺乏理解的迹象
【讨论】:
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)':{}
}
【讨论】: