我正在尝试制作一个包含 2 列的表格,标题用于姓名和薪水, 然后我尝试循环一个包含名称的数组和另一个包含工资的数组,但它没有按顺序出现,它们仅填充第一列(名称)
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<script>
var employeeName = ["Tom", "John", "Jack", "Sam", "Sarah", "Rachel", "Rick", "Sean", "Joe"];
for(var i = 0 ; i < employeeName.length ; i++)
{
document.write("<tr>");
document.write("<td>" + employeeName[i] + "</td>");
}
var employeeSalary = ["1000", "1500", "2000", "5000", "2500", "3000", "3500", "2500", "1750"];
for(var e = 0 ; e < employeeSalary.length ; e++)
{
document.write("<td>" + employeeSalary[e] + "</td>");
document.write("</tr>");
}
</script>
</tbody>
</table>
最佳答案
主要问题是,您将姓名和薪水存储在不同的数组中。最好将两个值都存储在一个对象中,并将对象存储在一个列表中。但根据您给定的结构,您必须按如下方式解决它:
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<script>
var employeeName = ["Tom", "John", "Jack", "Sam", "Sarah", "Rachel", "Rick", "Sean", "Joe"];
var employeeSalary = ["1000", "1500", "2000", "5000", "2500", "3000", "3500", "2500", "1750"];
for(var i = 0 ; i < employeeName.length ; i++)
{
document.write("<tr>");
document.write("<td>" + employeeName[i] + "</td><td>" + employeeSalary[i] + "</td>");
document.write("</tr>");
}
</script>
</tbody>
</table>
编辑
这是对下面评论中您的询问的回复。如果您想使用一组对象来解决问题,我建议这样做:
<table border="1">
<thead>
<tr>
<th>
Name
</th>
<th>
Salary
</th>
</tr>
</thead>
<tbody>
<script>
const employees = [
{name:"Tom", salary:"1000"},
{name:"John", salary:"1500"},
{name:"Jack", salary:"2000"},
{name:"Sam", salary:"5000"},
{name:"Sarah", salary:"2500"},
{name:"Rachel", salary:"3000"},
{name:"Rick", salary:"3500"},
{name:"Sean", salary:"2500"},
{name:"Joe", salary:"1750"}
];
employees.forEach( element => {
document.write("<tr>");
document.write("<td>" + element.name + "</td><td>" + element.salary + "</td>");
document.write("</tr>");
});
</script>
</tbody>
</table>
关于javascript数组循环到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466344/