当给出一个表格 `
var arr=[
{id:1001,name:"苹果 IphoneX",price:6900,num:2,info:"最新的苹果手机"},
{id:1002,name:"小米 10",price:3900,num:3,info:"最新的小米手机"},
{id:1003,name:"华为 meta10",price:8900,num:4,info:"最新的华为手机"},
{id:1004,name:"锤子手机",price:1900,num:1,info:"最新的锤子手机"},
{id:1005,name:"三星手机",price:4900,num:2,info:"最新的三星手机"},
{id:1006,name:"vivo 手机",price:2900,num:4,info:"最新的 vivo 手机"},
{id:1007,name:"魅族手机",price:1900,num:5,info:"最新的魅族手机"},
];
咱们须要把数组中的内容输入到表格里,且表格里该当有表头,表头信息是对象中的属性名,也就是咱们常说的 key,这就须要遍历数组而后输入内容在表格中,这个时候咱们该当首先把表头信息输入,这时须要遍历属性名,而后依照程序输入。这里应用 for···in 办法进行
for(var key in arr[j]){document.write("<td>"+key+"</td>");
}
而后对数组每个对象进行遍历,将属性名对应的属性值输入到表格对应地位。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border-collapse: collapse;
width: 800px;
}
td,th{
height: 30px;
line-height: 30px;
text-align: center;
font-size: 18px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<script>
var arr=[{id:1001,name:"苹果 IphoneX",price:6900,num:2,info:"最新的苹果手机"},
{id:1002,name:"小米 10",price:3900,num:3,info:"最新的小米手机"},
{id:1003,name:"华为 meta10",price:8900,num:4,info:"最新的华为手机"},
{id:1004,name:"锤子手机",price:1900,num:1,info:"最新的锤子手机"},
{id:1005,name:"三星手机",price:4900,num:2,info:"最新的三星手机"},
{id:1006,name:"vivo 手机",price:2900,num:4,info:"最新的 vivo 手机"},
{id:1007,name:"魅族手机",price:1900,num:5,info:"最新的魅族手机"},
];
var i=0,j=0;
document.write("<table>"); j=0;
for(i=0;i<arr.length;i++){if(i===0){document.write("<tr>");
for(var key in arr[j]){document.write("<td>"+key+"</td>");
}
document.write("</tr>");
}
else {document.write("<tr>");
for(let key in arr[j]){document.write("<td>"+arr[j][key]+"</td>");
}
document.write("</tr>");
j=j+1;
}
}
document.write("</table>");
</script>
</body>
</html>