<!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> .box{ width: 500px; } </style></head><body> <div class="box"> </div> <script> let users=[ { id:1, name:"Lynn", age:18 }, { id:2, name:"Lynn", age:18 }, { id:3, name:"Lynn", age:18 }, { id:4, name:"Lynn", age:18 } ] function init(){ //使用dom技术给box添加表格 let box=document.querySelector('.box'); let table=document.createElement('table'); // 将table元素添加到box box.appendChild(table); let thead=document.createElement('thead'); table.appendChild(thead); let tr=document.createElement('tr'); thead.appendChild(tr); let th=document.createElement('th'); th.appendChild(document.createTextNode('id')); tr.appendChild(th); th=document.createElement('th'); th.appendChild(document.createTextNode('姓名')); tr.appendChild(th); th=document.createElement('th'); th.appendChild(document.createTextNode('年龄')); tr.appendChild(th); let tbody=document.createElement('tbody'); table.appendChild(tbody); for(let user of users){ tr=document.createElement('tr'); let td=null; for(let key in user){ td=document.createElement('td'); // user[key]--取出变量key这个属性所对应的值 td.appendChild(document.createTextNode(user[key])); tr.appendChild(td); } tbody.appendChild(tr); } } window.onload=function(){ init(); } </script></body></html>