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

标签 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/

最佳答案

代码中的以下更正将解决您面临的问题。

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;

关于javascript - 当我指定一定数量的列时,乘法表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43406719/

相关文章:

javascript - 从 Silverlight 4.0 应用程序调用 JavaScript 函数

python - Python 中的字符串处理

php - CodeIgniter:为什么我的唯一表数据数组不包含任何值?

php - 使用用户定义的比较函数在_array 中搜索针

javascript - EMBER—断言失败 : Error while loading route: TypeError: Object [object Object] has no method 'addArrayObserver'

javascript - 如何在 Phaser 游戏中向每个用户显示不同的 map

javascript - 立即调用的简单 JavaScript 函数不起作用……为什么?

javascript - 从原始字符串形成树或节点

javascript - ECMASCRIPT6 Google 跟踪代码管理器错误 : Arrow function

c - 按升序排列 2 个数组 - C 编程