javascript - 为数组 html javascript 中的每个值创建新行
问题描述
我有这个数组:
var output = [[[a], [a1, a3, a5]], [[b], [b1, b2, b3]]]
我希望使用 javascript 在 html 中创建一个如下表:
a | b
-------
a1 | b1
a3 | b2
a5 | b3
但目前我只是这样:
a | b
--------------------
a1,a3,a5 | b1,b2,b3
使用此代码
var table = '<table ' + TABLEFORMAT + ' ">';
for (var row = 0; row < output.length; row++) {
table += '<tr>';
for (var col = 0; col < output[row].length; col++) {
if (output[row][col] === "" || 0) {
table += '<td>' + '' + '</td>';
} else
if (row === 0) {
table += '<th>' + output[col][row] + '</th>';
} else {
table += '<td>' + output[col][row] + '</td>';
}
}
table += '</tr>';
}
可以这样做吗?
解决方案
您可以将数据转换为类似结构的表格,然后创建表格。
const
pad = (array, tag) => array.map(v => `<${tag}>${v}</${tag}>`).join(''),
raw = [[['a'], ['a1', 'a3', 'a5']], [['b'], ['b1', 'b2', 'b3']]],
data = raw.reduce((r, [[h], a]) => {
r.header.push(h);
a.forEach((v, i) => (r.body[i] = r.body[i] || []).push(v));
return r;
}, { header: [], body: [] }),
table = document.createElement('table');
table.innerHTML = `<table>
<thead><tr>${pad(data.header, 'th')}</tr></thead>
<tbody>${pad(data.body.map(a => pad(a, 'td')), 'tr')}
</tbody>`;
document.body.appendChild(table);
推荐阅读
- python - 从列表中调用 lambda 函数
- java - 如何在邮递员中设置属性
- powershell - Powershell While 循环无法按预期工作
- wcf - faultCode=NO_PREFIX_SPECIFIED: 无法确定 ' 的命名空间
- php - 为什么这个接受邀请 php 脚本不起作用(不和谐 api 和 curl)
- python - 当前路径 % url 'accounts:logout' % 与其中任何一个都不匹配
- linux - 比较两个文件并提取不包含在第三个文件中的共同值
- hiveql - 如何在运行时从 Hive 脚本中的外部表将数据转储到临时表中(而不实际创建临时表)
- c# - 在 Azure Functions V1 中反序列化 json 时出错
- jquery - columnDefs 不能用于禁用对某些列的搜索?