使用字符串值访问javascript对象
我不明白为什么我不能访问这样的值:使用字符串值访问javascript对象,javascript,javascript-objects,Javascript,Javascript Objects,我不明白为什么我不能访问这样的值: 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); 到现在为止,我已经明白了不能这样做,但我
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']
您需要执行的操作
object.test[variable]
可以使用
和[]
访问对象
object.test.variable
正在寻找文本属性“variable”,它不存在。这个答案的可能重复的可能重复救了我的命!谢谢