【发布时间】:2012-07-18 13:49:01
【问题描述】:
我有一个多维数组,其中不会填充所有元素。我想将该数组的内容输出到 HTML 表中。我目前有这个:
for (var basketRowJuice = 0; basketRowJuice < 10; basketRowJuice++){
var outputName = "";
outputName = (basketArray[0][basketRowJuice]);
document.getElementById("basketJuiceName" + basketRowJuice).innerHTML = outputName;
}
for (var basketRowQuant = 0; basketRowQuant < 10; basketRowQuant++){
var outputQuant = 0;
outputQuant = (basketArray[1][basketRowQuant]);
document.getElementById("basketJuiceQuant" + basketRowQuant).innerHTML = outputQuant;
}
for (var basketRowPrice = 0; basketRowPrice < 10; basketRowPrice++){
var outputPrice = 0;
outputPrice = (basketArray[2][basketRowPrice]);
document.getElementById("basketJuicePrice" + basketRowPrice).innerHTML = outputPrice;
}
HTML 表格:
<table id="basket" cellpadding="0" cellspacing="0" summary="This table lists the items you have in your shopping basket">
<caption>Your basket</caption>
<tr>
<th scope="col">Juice name</th>
<th scope="col">Number of crates</th>
<th scope="col">Total price</th>
</tr>
<tr>
<td id="basketJuiceName0"></td>
<td id="basketJuiceQuant0"></td>
<td id="basketJuicePrice0"></td>
</tr>
<tr>
<td id="basketJuiceName1"></td>
<td id="basketJuiceQuant1"></td>
<td id="basketJuicePrice1"></td>
</tr>
<tr>
<td id="basketJuiceName2"></td>
<td id="basketJuiceQuant2"></td>
<td id="basketJuicePrice2"></td>
</tr>
<tr>
<td id="basketJuiceName3"></td>
<td id="basketJuiceQuant3"></td>
<td id="basketJuicePrice3"></td>
</tr>
<tr>
<td id="basketJuiceName4"></td>
<td id="basketJuiceQuant4"></td>
<td id="basketJuicePrice4"></td>
</tr>
<tr>
<td id="basketJuiceName5"></td>
<td id="basketJuiceQuant5"></td>
<td id="basketJuicePrice5"></td>
</tr>
<tr>
<td id="basketJuiceName6"></td>
<td id="basketJuiceQuant6"></td>
<td id="basketJuicePrice6"></td>
</tr>
<tr>
<td id="basketJuiceName7"></td>
<td id="basketJuiceQuant7"></td>
<td id="basketJuicePrice7"></td>
</tr>
<tr>
<td id="basketJuiceName8"></td>
<td id="basketJuiceQuant8"></td>
<td id="basketJuicePrice8"></td>
</tr>
<tr>
<td id="basketJuiceName9"></td>
<td id="basketJuiceQuant9"></td>
<td id="basketJuicePrice9"></td>
</tr>
</table>
但是,如果我的数组仅填充在 [0][9]、[1][9] 和 [2][9] 列中,那么在输出之前,我的 HTML 中会出现巨大的空行间隙.谁能建议一个更好的方法来做到这一点?也许这样我的 javascript 会为每个填充的数组元素插入一个表格行?
我是编程新手,所以请原谅我毫无疑问的冗长和不优雅的代码。
谢谢你, 乔恩
【问题讨论】:
-
那是奇怪的格式。你能发布你的确切html吗?
-
我试图粘贴我的 html 代码,但它不会显示!
-
粘贴它,然后选择它并按 Ctrl + K。
-
您的数组在没有数据或其他内容的情况下是否有“未定义”? (空,0(零))。如果第一行“没有数据”要显示,我相信你根本不想要它,对吧?第三个问题:是否可以在一个数组中包含一行值? (从名称、价格或数量上只有一两个?
标签: javascript html multidimensional-array