[英]Mapping 2D Array JavaScript into HTML Table
我有一個像這樣的二維數組
[["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]
我想把 map 二維數組的所有數據放到一個 html 表中,這里以我的 html 表代碼為例
<table id="codexpl">
<tr>
<th>No</th>
<th>Club</th>
<th>Points</th>
</tr>
<tr>
<td>row 1 col 1</td>
<td>row 1 col 2</td>
<td>row 1 col 3 </td>
</tr>
<tr>
<td>row 2 col 1</td>
<td>row 2 col 2</td>
<td>row 2 col 3 </td>
</tr>
</table>
那么如何解決呢? 謝謝你。
function createTable(tableData) { var table = document.createElement('table'), tableBody = document.createElement('tbody'); tableData.forEach(function(rowData) { var row = document.createElement('tr'); rowData.forEach(function(cellData) { var cell = document.createElement('td'); cell.appendChild(document.createTextNode(cellData)); row.appendChild(cell); }); tableBody.appendChild(row); }); table.appendChild(tableBody); document.body.appendChild(table); } createTable([["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]] );
遍歷您的數組,對於每個頂級元素,向表中添加一行。 然后,對於每個下一級元素,添加一個單元格並將元素的內容插入到表格單元格中。
你可以這樣做:
const toTable = (arr) =>
`<table id="codexpl">
<tr>
<th>No</th>
<th>Club</th>
<th>Points</th>
</tr>
${arr.map(
(item, index) =>
`<tr>
<td>${index + 1}</td>
<td>${item[0]}</td>
<td>${item[1]}</td>
</tr>`
).join('\n')}
</table>`
只需將數組傳遞給它,它就會返回 HTML 代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.