代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
var bgColor;
var list = [
{ id: '1', country: '中国', capital: '北京',},
{ id: '2', country: '美国', capital: '纽约',},
{ id: '3', country: '英国', capital: '伦敦',},
{ id: '4', country: '日本', capital: '东京',},
{ id: '5', country: '韩国', capital: '首尔',},
{ id: '6', country: '法国', capital: '柏林',}
];
window.onload = function myfunction() {
var body = window.document.getElementsByTagName("body")[0];
//创建表格
var table = window.document.createElement("table");
table.border = 1;
body.appendChild(table);
//创建标题行
var thead = window.document.createElement("thead");
var itemHead = list[0];
for (var index in itemHead) {
//创建标题单元格添加到thead
var th = window.document.createElement("th");
th.innerText = index;
thead.appendChild(th);
}
table.appendChild(thead);
//遍历对象,创建行和单元格
for (var i = 0; i < list.length; i++) {
var item = list[i];
//创建行
var tr = window.document.createElement("tr");
table.appendChild(tr);
for (var key in item) {
//创建单元格
var td = window.document.createElement("td");
td.innerText = item[key];
tr.appendChild(td);
}
}
}
</script>
</head>
<body>
</body>
</html>
实现效果如下: