【发布时间】:2018-01-25 13:12:32
【问题描述】:
解决方案
感谢瓦迪姆。我不得不将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
【问题讨论】:
-
显示的代码中没有对任何
consumptionPerHour的引用。请提供重现问题的minimal reproducible example -
谢谢,我已经做到了。
-
好的...您将其称为变量,但该变量不存在。
-
你的语句应该是
tableMaker('Consumption', 'consumptionPerHour'),我认为你需要传递字符串'consumptionPerHour'而不是变量。 -
如果你有给定属性consumptionPerHour的对象月份,你可以像month[0]['consumptionPerHour']一样访问它,如果你将propertyName作为参数传递,你可以像month[0][propertyName]一样使用它
标签: javascript function oop