我正在尝试使用多维数组创建一个包含所有十二生肖符号的表格(12列,n行,日期范围从1912年到2013年)。
我的代码如下,那就是我完全卡住的地方。
我的代码:
<script>
// declaring a 2D array
var signs = new Array(12);
for (var ndx = 0; ndx < 12; ndx++) {
signs[ndx] = new Array(2);
}
// The names first
signs[0][0] = "Rat";
signs[1][0] = "Ox";
signs[2][0] = "Tiger";
signs[3][0] = "Rabbit";
signs[4][0] = "Dragon";
signs[5][0] = "Snake";
signs[6][0] = "Horse";
signs[7][0] = "Goat";
signs[8][0] = "Monkey";
signs[9][0] = "Rooster";
signs[10][0] = "Dog";
signs[11][0] = "Pig";
// Next the image file names
signs[0][1] = "rat.gif";
signs[1][1] = "ox.gif";
signs[2][1] = "tgr.gif";
signs[3][1] = "rbt.png";
signs[4][1] = "drgn.png";
signs[5][1] = "snk.png";
signs[6][1] = "hrs.gif";
signs[7][1] = "gt.gif";
signs[8][1] = "mnky.png";
signs[9][1] = "rstr.gif";
signs[10][1] = "dog.gif";
signs[11][1] = "pig.gif";
document.write("<h2>");
document.write("</h2>");
document.writeln("<table border= '0' width = '100%'>");
document.writeln("<tr>");
for (var i = 0; i < SignNames.length; i++) {
document.writeln("<td>");
document.writeln(SignNames[i] + "<br />");
document.writeln("<img src='Images/" + SignImages[i] + "'/>");
document.writeln("</td>");
}
document.writeln("</tr>");
document.writeln("<tr>");
for (var i = 1912; i <= new Date().getFullYear(); i++) {
document.writeln("<td>" + i + "</td>");
tableCols++;
if (tableCols == 12) {
tableCols = 0;
document.writeln("</tr>");
}
}
document.writeln("</table>");
</script>
答案 0 :(得分:2)
代码中明显的问题是您声明了一个名为signs
的数组,然后在for循环中尝试以SignNames
的形式访问它。您需要匹配变量名称。您还使用了从未声明和初始化的变量tableCols
。我想这就是你要找的东西:
document.writeln("<table border= '0' width = '100%'>");
document.writeln("<tr>");
for (var i = 0; i < signs.length; i++) {
document.writeln("<td>");
document.writeln(signs[i][0] + "<br />");
document.writeln("<img src='Images/" + signs[i][1] + "'/>");
document.writeln("</td>");
}
document.writeln("</tr>");
document.writeln("<tr>");
var tableCols = 0; // <---- this variable wasn't initialised in your code
for (var i = 1912, d = new Date().getFullYear(); i <= d; i++) {
document.writeln("<td>" + i + "</td>");
if (++tableCols == 12) {
tableCols = 0;
document.writeln("</tr>");
}
}
document.writeln("</table>");
演示: http://jsbin.com/IZUnoSu/1/edit
此外,您的阵列初始化比必要的更复杂。您不需要使用new Array(12)
来创建包含12个元素的数组,您只需使用signs = []
声明一个空数组,然后开始添加它。但即使这样比你需要的更复杂,因为你可以用一个嵌套的数组文字在一个语句中声明整个事情:
var signs = [
["Rat","rat.gif"],
["Ox","ox.gif"],
["Tiger","tgr.gif"],
["Rabbit","rbt.png"],
["Dragon","drgn.png"],
["Snake","snk.png"],
["Horse","hrs.gif"],
["Goat","gt.gif"],
["Monkey","mnky.png"],
["Rooster","rstr.gif"],
["Dog","dog.gif"],
["Pig","pig.gif"]
];
答案 1 :(得分:0)
首先,我更喜欢你定义这样的数据:
var signs = [
{ name: "rat", image: "rat.gif" },
{ name: "ox", image: "ox.gif" },
...
{ name: "pig", image: "pig.gif" } // note: no trailing comma here
};
然后您可以编写signs[0].name
来访问该名称。这更容易阅读。
现在唯一需要解决的问题是,您将SignNames
替换为signs
,因为这是您的数组的名称。