且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用简单数组中的javascript创建动态html表

更新时间:2022-11-09 17:49:19

您可以迭代数组并创建一个新行,如果5的余数为零。 $ b

var array = [1,2,3,4,5,6,7,8,9,10], tr; array.forEach((v,i)=> {var td = document.createElement('td'); if(!(i%5)){tr = document.createElement('tr'); document。 getElementById('table0')。appendChild(tr);} td.appendChild(document.createTextNode(v)); tr.appendChild(td);});

< table id =table0>< / table>


I want to write some JavaScript to create a simple HTML table from an array that just contains numbers:

var array = [1,2,3,4,5,6,7,8,9,10];

The table should look like this:

1 2 3 4 5
6 7 8 9 10

But the JavaScript code should be dynamic depending on the arrays size (always a factor of 5 though).

I've tried a lot of stuff but it never works the way i want it to. What would be the easiest way to achieve this?

This is one of my tries.

var tableStart = "<table border>";
for (i = 0; i < arraySize/5; i++){
  var tableMiddle = "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>"
  if (arraySize/5 >= 2) {
    tableMiddle = tableMiddle + tableMiddle;
  }
};
var tableEnd = "</table>";
var table = tableStart.concat(tableMiddle, tableEnd);

as well as

var result = "<table border=1>";
for(var i=0; i<2; i++) {
    result += "<tr>";
    for(var j=0; j<array.length; j++){
        result += "<td>"+array[i]+"</td>";
    }
    result += "</tr>";
}
result += "</table>";

this one just results in two values of the array being displayed though a lot of times.

You could iterate the array and build a new row if the remainder with 5 is zero.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    tr;

array.forEach((v, i) => {
    var td = document.createElement('td');
    
    if (!(i % 5)) {
        tr = document.createElement('tr');
        document.getElementById('table0').appendChild(tr);
    }
    td.appendChild(document.createTextNode(v));
    tr.appendChild(td);
});

<table id="table0"></table>