如何使用带有数组数据的循环创建表

时间:2019-09-24 19:06:42

标签: javascript html

我需要从使用数组数据的循环创建表。

我使用的是示例代码,但是我在尝试弄清楚如何获得使用数组填充数据的循环时遇到了麻烦。我不知道我需要为功能部分添加什么内容,或者什至不必担心这一点?

<!Doctype html>
<html>
<head>
<script type="text/javascript">
function table()
{
    this.calcmul = calc;
}
 function calc(arg1,arg2)
 {
        var cars = ["Saab", "Volvo", "BMW"];
        var cars2 = ["Saab", "Volvo", "BMW"];
        return multi;   
 }
 var table2 = new table();  
</script>
</head>
<body>
<table border="solid 2px;" style="font-size:50px;">
    <thead><tr>
            <script>
            for(var j=1; j<=5; j++)
            {
                document.write("<th><label style= color:red;'>"+i+"</label></th>");
            }
            </script>
            </tr>
    </thead>
    <tbody>
        <script type="text/javascript"> 
for(var i =1; i<=5; i++)
{
    document.write("<tr>");
    for(var k=1; k<=2; k++)
        {
            var cars = i;
            var cars2 = k; 
            document.write("<td>"+table2.cars+"</td>"); 
        }
    document.write("</tr>"); 
}   
</script>
    </tbody>
</table>
</body>
</html>

我试图获取循环以创建表并列出数组中的数据

1 个答案:

答案 0 :(得分:0)

首先,您应该检查代码是否有错误!例如,您的</tbody>标签位于<script>标签之外。

要显示您在其中一个数组中的数据,我会这样做:

    <html>
    <head>
        <title></title>
    </head>
    <body>

        <table border="solid 2px;" style="font-size:50px;" id="myTable">

        </table>

    <script type="text/javascript">
            var cars = ["Saab", "Volvo", "BMW"];
            var table = document.getElementById("myTable");
            var tableHead = "<thead><th>Cars</th></thead>";
            table.innerHTML += tableHead; 
    //What the above line will do is add to "myTable" the element <thead> and the <th>, in this case it's just one.
            for(var i = 0; i<cars.length; i++)
            {   
    /*This loop will enter as long as index i isn't greater than all the elements of the cars array. 
In this case, as long as i doesn't exceed or equals 2, it will print things*/
                table.innerHTML += "<tbody><td>"+cars[i]+"</td></tbody>";
    /*Now, we add the element <tbody> with the respective tds,
 depending on the index it will print different things,
for example: in the first run, i = 0, so it will print the body as: <tbody><td>Saab</td></tbody>, why? well, because is the first element of the cars array, then it will continue to print the other values.*/
            }

    </script>
    </body>
    </html>

您可以在此处查看输出:https://jsfiddle.net/40wszykn/