从左到右,从上到下,将arr内容下载到表格单元格中?我的代码出了什么问题?如何解决问题?提前谢谢。
<button onclick="myFunction()></button>
<table id="myTable" border='1px'>
<tr>
<th>N</th>
<th>Name</th>
<th>Surname</th>
<th>tel.</th>
<th>email</th>
</tr>
</table>
var arr=[[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']];
function myFunction() {
createTable();
}
function createTable(){
var i,j;
var table = document.getElementById("myTable");
for( i=0; i<arr.length; i++ ) {
var row = table.insertRow(1);
for( j=0,k=0; j<5, k<arr[i].length;j++, k++ ) {
var cell = row.insertCell(0);
cell.innerHTML = arr[i][k];
}
}
}
答案 0 :(得分:0)
我不确定您的数据结构,但是如果您使用以下格式获取数据。
[ { N: 1, Name: 2, Surname: 3, Tel: 4, email: 'a' },
{ N: 5, Name: 6, Surname: 7, Tel: 8, email: 'b' },
{ N: 9, Name: 10, Surname: 11, Tel: 12, email: 'c' } ]
您可以使用以下tableMaker
功能。它将属性作为标题(如果第二个参数提供为true
)并将值作为相应的单元格来生成HTML文本。所以这里的内容如下:
var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return rows.length ? "<table>" + rows + "</table>" : "";
},
arr = [[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']],
tableObj = arr.map(e => ({N: e[0], Name: e[1], Surname : e[2], Tel: e[3], email: e[4]})),
tableHTML = tableMaker(tableObj,true);
document.write(tableHTML);