如何从对象数组创建 HTML 表格?

Rap*_*rRV 0 html javascript arrays javascript-objects

我需要从对象数组生成一个表。

例如,数组是:

let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]
Run Code Online (Sandbox Code Playgroud)

HTML 输出应该是:

姓名 分数
玩家1 10
玩家2 7
玩家3 3

我想不出通过普通 JS 实现这一点的方法。另外,创建表格后,我将如何对其应用CSS?

任何帮助,将不胜感激。

Die*_*ita 6

您可以循环遍历数组,并为每个元素添加一行到新伪造的表中,该表将在末尾添加到文档中。

这是一个演示:

let players = [
  {name: 'Player1',score:10},
  {name: 'Player2',score: 7},
  {name: 'Player3',score:3}
];

const newTable = document.createElement("table");
newTable.innerHTML = "<thead><th>Player</th><th>Score</th></thead>";
for(player of players){
    const newRow = document.createElement("tr");
    const tdPlayer = document.createElement("td");
    const tdScore = document.createElement("td");
    tdPlayer.textContent = player.name;
    tdScore.textContent = player.score;    
    newRow.appendChild(tdPlayer);
    newRow.appendChild(tdScore);
    newTable.appendChild(newRow);
}

const target = document.getElementById('target');
target.appendChild(newTable);
Run Code Online (Sandbox Code Playgroud)
table{
  border: solid 1px black;
}

table td{
  border: solid 1px black;
}
Run Code Online (Sandbox Code Playgroud)
<div id="target">
</div>
Run Code Online (Sandbox Code Playgroud)