将二维数组 JavaScript 映射到 HTML 表格

我有一个像这样的二维数组


[["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]

我想将 2D Array 的所有数据映射到一个 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>

那么如何解决呢?谢谢。


慕运维8079593
浏览 99回答 3
3回答

慕标5832272

function createTable(tableData) {&nbsp; var table = document.createElement('table')&nbsp; &nbsp; , tableBody = document.createElement('tbody');&nbsp; tableData.forEach(function(rowData) {&nbsp; &nbsp; var row = document.createElement('tr');&nbsp; &nbsp; rowData.forEach(function(cellData) {&nbsp; &nbsp; &nbsp; var cell = document.createElement('td');&nbsp; &nbsp; &nbsp; cell.appendChild(document.createTextNode(cellData));&nbsp; &nbsp; &nbsp; row.appendChild(cell);&nbsp; &nbsp; });&nbsp; &nbsp; tableBody.appendChild(row);&nbsp; });&nbsp; table.appendChild(tableBody);&nbsp; document.body.appendChild(table);}createTable([["Manchester City", 92], ["Liverpool", 82], ["Tottenham", 78], ["Chelsea", 78], ["Manchester United", 72], ["Arsenal", 69]]);

手掌心

遍历您的数组,对于每个顶级元素,向表中添加一行。然后,对于每个下一级元素,添加一个单元格并将元素的内容插入到表格单元格中。

繁花不似锦

你可以这样做:const toTable = (arr) =>&nbsp; `<table id="codexpl">&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>No</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Club</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Points</th>&nbsp; &nbsp; </tr>&nbsp; &nbsp; ${arr.map(&nbsp; &nbsp; (item, index) =>&nbsp; &nbsp; &nbsp; `<tr>&nbsp; &nbsp; &nbsp; <td>${index + 1}</td>&nbsp; &nbsp; &nbsp; <td>${item[0]}</td>&nbsp; &nbsp; &nbsp; <td>${item[1]}</td>&nbsp; </tr>`&nbsp; ).join('\n')}</table>`只需将数组传递给它,它就会返回 HTML 代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript