我不明白为什么我不能访问这样的值:
object = {
test:{
value: "Hello world"
}
}
variable = "value";
//this gives me "Hello world"
console.log(object.test.value);
//this gives me undefined error
console.log(object.test.variable);
现在我知道不能这样做,但我仍然需要为变量赋予一些值,然后使用该变量来访问对象值。
最佳答案
这样做:
console.log(object.test[variable]);
用点来实现就是使用文字属性名称。即,object.test.value
等于 object.test['value']
。
关于javascript - 使用字符串值访问 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11214013/