我正在创建一个应该从数组中获取数据的函数(结果)并将它们放入表的特定列中。数组除以数字,用于标识应在其中输入以下数据的列。
例如:
var results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
col 1: 'aaaaaa', 'bbb';
col 2: 'ccc'; etc.
我已经在很多方面尝试过这种方法,而且我无法让它发挥作用。
目前代码看起来像这样。我不确定该怎么做:
var results = [1, 'aaaaaa','bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
var k = 0;
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
if (i > 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'PN'));
}
else if (i == 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'TYPE'));
}
else if (j > 0 && i == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'LABLE ' + j));
}
else if (j > 0 && i > 0 && results[i] != k) {
row.cells[k].appendChild(document.createTextNode(content + results[i]));
}
}
table.appendChild(row);
k++;
}
return table;
}
function load() {
document.getElementById('tablearea')
.appendChild(populateTable(null, 9, 10, ""));
}
答案 0 :(得分:0)
首先将结果格式化为:
{
1: ['aaaaaa', 'bbb'],
2: ['ccc'],
3: ['dddd', 'eeee'],
4: ['fff']
}
然后生成表格:
const results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff', 5, 'ggg', 'hhhh', 'iiii'];
// First format the results
const formattedResults = {};
let columnIndex = 0;
results.forEach(elt => {
if (!isNaN(elt)) {
formattedResults[elt] = [];
columnIndex = elt;
} else {
formattedResults[columnIndex].push(elt);
}
});
// Then generate the table
const table = document.createElement('table');
const columnKeys = Object.keys(formattedResults);
const maxRows = Math.max(...columnKeys.map(key => formattedResults[key].length));
for (let i = 0; i < maxRows; i = i + 1) {
const tr = document.createElement('tr');
columnKeys.forEach(colKey => {
const td = document.createElement('td');
if (formattedResults[colKey][i] !== undefined) {
td.textContent = formattedResults[colKey][i];
tr.appendChild(td);
}
});
table.appendChild(tr);
}
document.getElementById('tableArea').appendChild(table);
&#13;
<div id="tableArea"></div>
&#13;