【问题标题】:Reading a csv file in, converting it to a 2-d array and then displaying it as a table on HTML读取 csv 文件,将其转换为二维数组,然后将其显示为 HTML 上的表格
【发布时间】:2021-10-25 17:41:38
【问题描述】:

我编写了一个脚本来接受 csv 文件,然后将 csv 文件转换为二维数组。我可以看到我保存的对象实际上是一个数组,方法是:

console.log(Array.isArray(data));

返回true,我可以使用

console.table(data);

我现在正在尝试将二维数组的内容显示为网页上的 html 表格,这是我目前得到的结果:

function createTable(tableData) {
  var table = document.createElement('table');
  var row = {};
  var cell = {};

  tableData.forEach(function(rowData) {
    row = table.insertRow(-1);
    rowData.forEach(function(cellData) {
      cell = row.insertCell();
            cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
}

调用

createTable(data);

我收到此错误:

(index):69 Uncaught TypeError: rowData.forEach 不是函数

【问题讨论】:

    标签: javascript html arrays


    【解决方案1】:

    您的代码工作正常,所以问题一定出在数据数组上。 而不是 console.table(data),这样做:

    console.log(data);
    

    对于让数据 = [ [1,3,5], [4,8,12] ];输出是:

    Array [ (3) […], (3) […] ]
    ​0: Array(3) [ 1, 3, 5 ]
    ​1: Array(3) [ 4, 8, 12 ]
    ​length: 2
    ​<prototype>: Array []
    

    如果您看到的不同,那应该会引导您找出问题所在。

    或者...将你的代码简化为这个,看看你得到了什么:

    tableData.forEach(function(rowData) {
        console.log(rowData); 
        rowData.forEach(function(cellData) {
             console.log(cellData);
        });
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多