解决方案
感谢瓦迪姆。我不得不将 months[i].anArray[b]
更改为 months[i][anArray][b]
我有一个月份数组,其中包含每个月的一个对象。每个月都有一些属性,包括数组,例如:
months[0].consumptionPerHour
返回 24 个值,可以使用 months[0].consumptionPerHour[0-23]
我正在尝试创建一个创建表的函数,该函数具有表的名称和我希望访问的数组的名称作为函数的参数,如下所示:
function tableMaker(tableName, anArray) {
$("#outputs").append(
"<table id='table" + totalTables + "'>"
"<tr id='header" + totalTables + "'><td>" + tableName + "</td>"
);
for(i=0;i<12;i++) {
$("#header" + totalTables).append("<td>" + months[i].shortName + "</td>");
}
for(b=0;b<24;b++) {
$("#table" + totalTables).append(
"<tr id='table" + totalTables + "row" + b + "'><td>" + hours[b] + "</td>"
);
for(i=0;i<12;i++) {
$("#table" + totalTables + "row" + b).append("<td>" + months[i].anArray[b] + "</td>");
}
}
}
出于某种原因,如果我传递一个我知道存在的属性名称作为参数,例如 tableMaker('Consumption', consumptionPerHour)
,它只会返回以下内容:
Uncaught ReferenceError: consumptionPerHour is not defined
at <anonymous>:1:22
但是,这是通过控制台返回的:
months[0].consumptionPerHour
(24) [0.1567002086212712, 0.1567118400503239, ...]
months[0].consumptionPerHour[0]
0.1567002086212712
最佳答案
要使用变量访问对象属性,您需要使用 []
表示法并且变量需要是字符串
所以我认为你想要的是
tableMaker('Consumption', 'consumptionPerHour')
然后在函数中使用:
months[i][anArray][b]
关于javascript - 如何使用对象属性作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443707/