当我指定一定数量的列时,乘法表不起作用

时间:2017-04-14 06:58:24

标签: javascript arrays

我不明白为什么当我指定的列少于行时,HTML表格不会构建。

var table2 = Array(10);
for (var i = 0; i < table2.length; i++) {

// If I change Array(5) to something like Array(10) it doesn't work
table2[i] = Array(5);
}


var code = "<table cellpadding=\"15\" cellspacing=\"0\"><tr>"

for (row = 1; row <= table2.length; row++) {
  for (col = 1; col <= table2[col].length; col++) {
    code += "<td>" + col * row + "</td>";
  }
code += "</tr>";
};

document.getElementById('fart').innerHTML = code;

链接:https://jsfiddle.net/pz4p9nff/

5 个答案:

答案 0 :(得分:1)

试试这个

var code = "<table cellpadding=\"15\" cellspacing=\"0\">"

for (row = 1; row <= 10; row++) {
    code += '<tr>';
    for (col = 1; col <= 5; col++) {
        code += "<td>" + col * row + "</td>";
    }
    code += "</tr>";
};

document.getElementById('fart').innerHTML = code;

答案 1 :(得分:1)

您的代码中的以下更正将解决您遇到的问题。

var table2 = Array(10); //Init the amount of rows in your table
var code = "<table cellpadding=\"15\" cellspacing=\"0\">";

//Don't forget: arrays are zero based. Starting at 1 will skip row with index 0
for (row = 0; row < table2.length; row++){

    //Initialize each row with a fixed amount of columns... 
  //no need to do this in a seperate loop
    table2[row] = Array(5); 
  //Open each row properly
  code += "<tr>"; 

  //Loop the columns of each row
  for (col = 0; col < table2[row].length; col++){
    code += "<td>" + col*row + "</td>";
  }

  code += "</tr>";
};

code += "</table>"; //Close your table properly

document.getElementById('fart').innerHTML = code;

答案 2 :(得分:1)

您必须按如下方式更正代码;

&#13;
&#13;
var table2 = Array(10);
for (var i = 0; i < table2.length; i++){ 

// If I change Array(5) to something like Array(10) it doesn't work
	table2[i] = Array(10)
}
  

var code = "<table cellpadding=\"15\" cellspacing=\"0\"><tr>"

for (row = 1; row < table2.length; row++){ // !!! use < not <=
    for (col = 1; col < table2[row].length; col++){ // !!! use < not <= and table2[row]
      code += "<td>" + col*row + "</td>";
    }
  code += "</tr>";
  };
 
document.getElementById('fart').innerHTML = code;
&#13;
<div id ="fart">

</div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

按如下方式更新列交互循环。

for (col =0; col < table2[row].length; col++) {
  code += "<td>" + col * row + "</td>";
}

答案 4 :(得分:0)

初始化<tr>

时,您需要删除code代码
var code = "<table cellpadding=\"15\" cellspacing=\"0\">"

对于每个row,都应添加新的<tr>标记。 for的内部col循环限制应为table2.[row-1].length。由于您使用row作为值变量而不是索引,因此它的值从1开始,但索引通常从0开始。

for (row = 1; row <= table2.length; row++){
    code += "<tr>";
    for (col = 1; col <= table2[row-1].length; col++){
        code += "<td>" + col * row + "</td>";
    }
code += "</tr>";
};    

您还需要关闭</table>代码。

code+="</table>";

更新了https://jsfiddle.net/pz4p9nff/4/