我有以下对象数组,其中按编号存储公交车路线,然后按名称存储:
var routearray =[
ruta01 =
{
via01: "Progress",
via02: "Ten",
via03: "S",
via04: "Maria"
},
ruta02 =
{
via01: "Exterior",
via02: "Interior"
},
ruta03 =
{
via01: "University",
via02: "Henry St"
},];
我有以下代码,我想用它来访问每个属性的值:
for(i=0;i<routearray.length;i++) //iterates through the array's objects
{
var props = Object.keys(routearray[i]); //array that stores the object properties
for(j=0;j<props.length;j++) //iterates through specific object properties
{
console.log(props[j]); //shows the property names
var propertystring = String(props[j]); //transforms the property name into string
console.log(routearray[i].propertystring]; //should access the property value
}
}
当代码的最后一行执行时,我在控制台中得到 8 个“未定义”结果。如果我把它改成这样:
console.log(routearray[i].via01];
它工作得很好,但我不确定如果字符串应该正常工作,为什么它不能访问该值。 我究竟做错了什么?有更好的办法吗?
最佳答案
应该是:
console.log(routearray[i][propertystring]);
一般来说,当您执行“someObject.key”时,实际值“key”必须作为“someObject”中的属性存在。但是,如果您执行“someObject[key]”,则变量“key”中包含的值必须作为属性存在于“someObject”中。
关于javascript - 如何在 JavaScript 中动态获取对象的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36900392/