请把下面数据中的对象打印出来: students = [ {uid: 1, name: ‘小明’, age: 18, gender: ‘男’, hometown: ‘河北省’ }, {uid: 2, name: ‘小红’, age: 19, gender: ‘女’, hometown: ‘河南省’ }, {uid: 3, name: ‘小刚’, age: 17, gender: ‘男’, hometown: ‘山西省’ }, {uid: 4, name: ‘小丽’, age: 18, gender: ‘女’, hometown: ‘山东省’ } ]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding:0;
margin:0;
}
table{
width:500px;
margin:100px auto;
border-collapse:collapse;/*边框合并模式*/
text-align:center;
}
td,th{
border:1px solid #333;
}
thead tr{
height:40px;
background-color: #cccccc;
}
</style>
</head>
<body>
<script>
let students = [
{ name: '小明', age: 18, gender: '男', hometown: '河北省' },
{ name: '小红', age: 19, gender: '女', hometown: '河南省' },
{ name: '小刚', age: 17, gender: '男', hometown: '山西省' },
{ name: '小丽', age: 18, gender: '女', hometown: '山东省' }
]
document.write(`
<table>
<caption>
<h2> 学生列表</h2>
</caption>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</tr>
</thead>
`)
for(i = 0; i < students.length ; i ++) {
let a = students[i]
document.write(`
<tbody>
<tr>
<td>${i}</td>
<td>${a.name}</td>
<td>${a.age}</td>
<td>${a.gender}</td>
<td>${a.hometown}</td>
</tr>
</tbody>
`)
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding:0;
margin:0;
}
table{
width:500px;
margin:100px auto;
border-collapse:collapse;/*边框合并模式*/
text-align:center;
}
td,th{
border:1px solid #333;
}
thead tr{
height:40px;
background-color: #cccccc;
}
</style>
</head>
<body>
<table>
<caption>
<h2> 学生列表</h2>
</caption>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
let students = [
{uid: 1, name: '小明', age: 18, gender: '男', hometown: '河北省' },
{uid: 2, name: '小红', age: 19, gender: '女', hometown: '河南省' },
{uid: 3, name: '小刚', age: 17, gender: '男', hometown: '山西省' },
{uid: 4, name: '小丽', age: 18, gender: '女', hometown: '山东省' }
]
// 往tbody里面创建行,有几个人(通过数组的长度)我们就创建几行
let tbody=document.querySelector("tbody");
for (let i = 0; i < students.length; i++) {
let tr = document.createElement("tr")
tbody.appendChild(tr)
//往tr每一行里面创建单元格(跟数据有关系的3个单元格),td单元格的数量取决于每个对象的属性个数 for循环遍历对象 students[i]
for (let k in students[i]) {
let td = document.createElement("td") // 创建单元格
td.innerHTML = students[i][k] //把对象的属性给单元格
tr.appendChild(td)
}
}
</script>
</body>
</html>