从不同的数组大小创建表

时间:2019-01-18 05:48:45

标签: javascript html

我有5个数组,

Col1 = [1];
Col2 = [1,2];
Col3 = [1,2,3];
Col4 = [1,2,3,4];
Col5 = [1,2,3,4,5];

是否可以从这些看起来像这样的数组中创建表?

enter image description here

如何制作一个表,其列顺序与数组中的列顺序相同。另外,如果我在这些数组中的任何一个中添加一些数据,则更改应动态反映在表中。

这是一个新示例,其中添加了另一组数组

enter image description here

2 个答案:

答案 0 :(得分:2)

var Col1 = [1];
var Col2 = [1, 2];
var Col3 = [1, 2, 3];
var Col4 = [1, 2, 3, 4];
var Col5 = [1, 2, 3, 4, 5];
var columns = [Col1, Col2, Col3, Col4, Col5];

addColumnsToTable(columns);
addColumnsToTable(columns);

function addColumnsToTable(columns) {
  var rowsCount = Math.max.apply(null, columns.map(x => x.length));

  var res = '';
  for (var i = 0; i < rowsCount; i++) {
    var row = '<tr>';
    for (var column of columns)
      row += `<td>${column[i] || ''}</td>`;
    row += '</tr>';
    res += row;
  }

  document.getElementById('content').innerHTML += res;
    
  var head = document.getElementById('head');
  if(!head.innerHTML.trim())
    head.innerHTML = columns.map((x, i) => `<th>Col${i + 1}</th>`).join('');  
}
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
#head > th{
  color: red;
}
<table>
  <thead>
    <tr id='head'>
    </tr>
  </thead>
  <tbody id='content'>
  </tbody>
</table>

答案 1 :(得分:0)

是的,您可以执行-在数组上嵌套forEach,然后创建并追加行:

var table = document.getElementById("table");

Col1 = [1];
Col2 = [1, 2];
Col3 = [1, 2, 3];
Col4 = [1, 2, 3, 4];
Col5 = [1, 2, 3, 4, 5];

[Col1, Col2, Col3, Col4, Col5].forEach((a, i) => {
  var row = document.createElement("tr");
  [Col1, Col2, Col3, Col4, Col5].forEach((arr) => {
    var cell = document.createElement("td");
    if (arr.length) {
      cell.innerText = arr[0];
      arr.shift();
    }
    row.appendChild(cell);
  });
  table.appendChild(row);
});
<table id="table" border="1">
  <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    <th>Col 3</th>
    <th>Col 4</th>
    <th>Col 5</th>
  </tr>
</table>

如果要使用JavaScript创建整个表,则:

var table = document.createElement("table");
table.setAttribute("border", "1");
table.innerHTML = "<tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th></tr>";

Col1 = [1];
Col2 = [1, 2];
Col3 = [1, 2, 3];
Col4 = [1, 2, 3, 4];
Col5 = [1, 2, 3, 4, 5];

[Col1, Col2, Col3, Col4, Col5].forEach((a, i) => {
  var row = document.createElement("tr");
  [Col1, Col2, Col3, Col4, Col5].forEach((arr) => {
    var cell = document.createElement("td");
    if (arr.length) {
      cell.innerText = arr[arr.length - 1];
      arr.pop();
    }
    row.appendChild(cell);
  });
  table.appendChild(row);
});

document.body.appendChild(table);