我不明白为什么我不能访问这样的值:
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”,但该属性不存在。
其实可以通过JSON路径实现