试图用JS从数组中以HTML形式显示表



我有一个包含五个用户的数组,我正试图在HTML中的表上显示它。我认为我的JS代码做得很好(或者至少我是这么认为的…哈哈…我对编码很陌生(,我只是不明白如何在HTML中显示数组的整个表内容。我尝试了.innerHTML,但它不起作用。

希望有人能弄清楚。提前感谢S:(

let myArr = []; 
function User (name, lastname, city, email) {
this.name = name;
this.lastname = lastname;
this.city = city;
this.email = email;
}
let userOne = new User('Leonardo', 'Parigini', 'Santorini', 'leoparigini@gmail.com');
let userTwo = new User('Edoardo', 'Merlini', 'Monaco', 'edomerlini@gmail.com');
let userThree = new User('Nicole', 'De Lellis', 'Milano', 'nickydelellis@gmail.com');
let userFour = new User('Jasmine', 'Scherzinger', 'Los Angeles', 'jazzylax@gmail.com');
let userFive = new User('Emily', 'Knowles', 'San Francisco', 'emilyknow@gmail.com');

myArr.push(userOne, userTwo, userThree, userFour, userFive);
console.log(myArr); 
let myNewArr = [...myArr];
console.log(myNewArr); 
var table = document.querySelector('#myTable')
table.innerHTML = '<tr><td>' + myNewArr + '</td></tr>'
<body class="bg-info">
<div class="container">
<h1 class="display-3">USER LIST</h1>
<table class="table table-dark table-striped" id="myTable">
<thead>
<tr>
<th scope="col" id="nome">Nome</th>
<th scope="col" id="cognome">Cognome</th>
<th scope="col" id="citta">Città</th>
<th scope="col" id="email">Email</th>
</tr>
</thead>
<tbody>
<!--   <tr id="myListHTML">   </tr>

<th scope="row"></th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>

<tr>
<th sco pe="row">3</th>
<td colspan="2">Larry the Bird</td>
<td>@twitter</td>
</tr>
</tbody> -->
</table>

</div>

这里有一个有用的方法

我使用地图和模板文字

function User(name, lastname, city, email) {
this.name = name;
this.lastname = lastname;
this.city = city;
this.email = email;
}
let myArr = [
new User('Leonardo', 'Parigini', 'Santorini', 'leoparigini@gmail.com'),
new User('Edoardo', 'Merlini', 'Monaco', 'edomerlini@gmail.com'),
new User('Nicole', 'De Lellis', 'Milano', 'nickydelellis@gmail.com'),
new User('Jasmine', 'Scherzinger', 'Los Angeles', 'jazzylax@gmail.com'),
new User('Emily', 'Knowles', 'San Francisco', 'emilyknow@gmail.com')
]
//console.log(myArr);
document.querySelector("#myTable tbody").innerHTML = myArr.map(user => `<tr><td>${user.name}</td><td>${user.lastname}</td><td>${user.city}</td><td>${user.email}</td></tr>`).join('')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
<div class="container">
<h1 class="display-3">USER LIST</h1>
<table class="table table-dark table-striped" id="myTable">
<thead>
<tr>
<th scope="col">Nome</th>
<th scope="col">Cognome</th>
<th scope="col">Città</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

最新更新