gpt4 book ai didi

javascript - 在动态表javascript中显示对象数组

转载 作者:行者123 更新时间:2023-12-01 07:55:13 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Convert json data to a html table [closed]

(4 个回答)


7年前关闭。




我想使用 javascript 在动态表中显示对象数组。

var rows=[{ name : "John", age:20, email: "xx@hotmail.com"},
{ name : "Jack", age:50, email: "xxx@hotmail.com"},
{ name : "Son", age:45, email: "xxxx@hotmail.com"}
........................etc
];

这就是它的外观。我想知道如何将其显示为动态表。

最佳答案

这就是你的做法:
Javascript 解决方案:
FIDDLE :

var rows = [{
name: "John",
age: 20,
email: "xx@hotmail.com"
}, {
name: "Jack",
age: 50,
email: "xxx@hotmail.com"
}, {
name: "Son",
age: 45,
email: "xxxx@hotmail.com"
}];

var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
html+="<tr>";
html+="<td>"+rows[i].name+"</td>";
html+="<td>"+rows[i].age+"</td>";
html+="<td>"+rows[i].email+"</td>";

html+="</tr>";

}
html+="</table>";
document.getElementById("box").innerHTML = html;
jQuery 解决方案:
FIDDLE
var rows = [{
name: "John",
age: 20,
email: "xx@hotmail.com"
}, {
name: "Jack",
age: 50,
email: "xxx@hotmail.com"
}, {
name: "Son",
age: 45,
email: "xxxx@hotmail.com"
}];

$(document).ready(function () {
var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
html+="<tr>";
html+="<td>"+rows[i].name+"</td>";
html+="<td>"+rows[i].age+"</td>";
html+="<td>"+rows[i].email+"</td>";

html+="</tr>";

}
html+="</table>";
$("div").html(html);
});
jQuery解决方案2:
FIDDLE
var rows = [{
name: "John",
age: 20,
email: "xx@hotmail.com"
}, {
name: "Jack",
age: 50,
email: "xxx@hotmail.com"
}, {
name: "Son",
age: 45,
email: "xxxx@hotmail.com"
}];

const Array2Table = (arr) => {
let Table = [];
let top_row = [];
let rows = [];

for (let i = 0; i < arr.length; i++) {
let cells = [];

for (let property in arr[i]) {
if (top_row.length < Object.keys(arr[i]).length) {
top_row.push(`<th scope="col">${property}</th>`);
}
if (arr[i][property] === null) {
cells.push(`<td>${null}</td>`);
} else {
cells.push(`<td>${arr[i][property]}</td>`);
}
}

rows.push(`<tr>${cells.join("")}</tr>`);
}

Table.push(`<table class="table card-table table-striped">`);
Table.push(`<thead>${top_row.join("")}</thead>`);
Table.push(`<tbody>${rows.join("")}<tbody>`);
Table.push("</table>");
return Table.join("");
}

$(function() {
let html = Array2Table(rows);
$("div").html(html);
});

关于javascript - 在动态表javascript中显示对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com