當給出一個表格`
var arr=[html
{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>"); }
而後對數組每一個對象進行遍歷,將屬性名對應的屬性值輸出到表格對應位置。code
<!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>