Javascript 从数组中添加行 headers 到 table?

Javascript add row headers to table from an array?

我有一个填充 table 的二维数组。有没有办法一直向左插入一列?

//function to create the table
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;
      let cellVal = cellData;
      //make cells different shades of green and red for pos/neg (based on %)
      if (cellVal > 0) {
        cell.style.backgroundColor = '#00e100';
      } else if (cellVal < 0) {
        cell.style.backgroundColor = 'red';
      }
    });
  });
  document.body.appendChild(table);
}
createTable(transpose_array);

由于颜色条件,我不想向 table 添加值,我只想向 [=23= 的 y-axis 的每一行添加 headers ] 使用我拥有的数组中的值。

图片如下:

forEach() 回调获取包含数组索引的第二个参数,您可以使用它来索引标题数组,并将其作为每行中的第一个单元格插入。

//function to create the table
function createTable(tableData, row_headings) {
  var table = document.createElement('table');
  var row = {};
  var cell = {};
  
  tableData.forEach(function(rowData, i) {
    row = table.insertRow(-1);
    cell = row.insertCell();
    cell.textContent = row_headings[i];
    rowData.forEach(function(cellData) {
      cell = row.insertCell();
      cell.textContent = cellData;
      let cellVal = cellData;
      //make cells different shades of green and red for pos/neg (based on %)
      if (cellVal > 0) {
        cell.style.backgroundColor = '#00e100';
      } else if (cellVal < 0) {
        cell.style.backgroundColor = 'red';
      }
    });
  });
  document.body.appendChild(table);
}
createTable(transpose_array, price_array);