简体   繁体   English

Javascript 从数组中向表中添加行标题?

[英]Javascript add row headers to table from an array?

I have a 2d array that populates a table.我有一个填充表格的二维数组。 Is there a way to insert a column all the way to the left?有没有办法一直向左插入一列?

//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);

I dont want to add values to the table because of the color conditions, Id just like to add headers to each row on the y-axis of the table using values from an array I have.由于颜色条件,我不想向表中添加值,我只想使用我拥有的数组中的值向表的 y 轴上的每一行添加标题。

Image is below:图片如下: 在此处输入图像描述

The forEach() callback gets a second argument containing the array index, you can use this to index into the headings array, and insert that as the first cell in each row. 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM