gpt4 book ai didi

javascript - 如何使用 JavaScript 打印对象数组

转载 作者:行者123 更新时间:2023-11-30 12:19:28 25 4
gpt4 key购买 nike

我声明了 4 个对象并将它们放入数组 myArray 中。现在我想使用 JavaScript 在表格中打印这个数组。

这是我的代码:

<style>
#div1
{
background:pink;
width:100%;
height:80%;
padding:5%;
border:1px solid black;
}
table,th,td {
border:1px solid black;
padding:1px;
}
</style>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
#div1
{
background:pink;
width:100%;
height:80%;
padding:5%;
border:1px solid black;
}
table,th,td {
border:1px solid black;
padding:1px;
}
</style>
</head>
<body>
<div id="div1">
<table>
<script>
var student1 = { Name: "Amol", rno: 1, Class: "MCA", Div: "A" };
var student2 = { Name: "Sagar", rno: 2, Class: "MBA", Div: "B" };
var student3 = { Name: "Bhushan", rno: 1, Class: "MMM", Div: "C" };
var student4 = { Name: "Nachiket", rno: 1, Class: "MPM", Div: "A" };

var MyArray = [];
myArray[0].push(student1);
myArray[1].push(student2);
myArray[2].push(student3);
myArray[3].push(student4);

//document.write("<tr><th>"+ Name+</th>"+
//"<th>RollNumber</th>"
//"<th>Class</th>"
//"<th>Division</th>");
//"</tr>"
alert("p");

for (var i = 0; i < MyArray.length; i++) {
document.write("<tr><td>" + MyArray[i].Name + "</td>");
document.write("<td>" + MyArray[i].rno + "</td>");
document.write("<td>" + MyArray[i].Class + "</td></tr>");
document.write("<td>" + MyArray[i].Div + "</td></tr></br>");
}
</script>
</table>
</div>
</body>
</html>

最佳答案

您的代码中几乎没有错误:

  1. 您已经交替使用了 MyArraymyArray,因此请保持一致。
  2. 当你压入数组中的项目时,不要对它使用索引。正确的语法是:myArray.push(student1);

所以你的代码变成:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
#div1
{
background:pink;
width:100%;
height:80%;
padding:5%;
border:1px solid black;

}
table,th,td {
border:1px solid black;
padding:1px;
}
</style>

</head>
<body>
<div id="div1">
<table>
<script>
var student1 = { Name: "Amol", rno: 1, Class: "MCA", Div: "A" };
var student2 = { Name: "Sagar", rno: 2, Class: "MBA", Div: "B" };
var student3 = { Name: "Bhushan", rno: 1, Class: "MMM", Div: "C" };
var student4 = { Name: "Nachiket", rno: 1, Class: "MPM", Div: "A" };

var myArray = [];
myArray.push(student1);
myArray.push(student2);
myArray.push(student3);
myArray.push(student4);

//document.write("<tr><th>"+ Name+</th>"+
//"<th>RollNumber</th>"
//"<th>Class</th>"
//"<th>Division</th>");
//"</tr>"
alert("p");
for (var i = 0; i < myArray.length; i++) {

document.write("<tr><td>" + myArray[i].Name + "</td>");
document.write("<td>" + myArray[i].rno + "</td>");
document.write("<td>" + myArray[i].Class + "</td></tr>");
document.write("<td>" + myArray[i].Div + "</td></tr></br>");
}
</script>
</table>

</div>

</body>
</html>

查看工作插件:“http://plnkr.co/edit/D3zEFzOPqJWLHOTd2KvN?p=preview

关于javascript - 如何使用 JavaScript 打印对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31511370/

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