Create dynamic html table using javascript from simple array

后端 未结 3 920
暖寄归人
暖寄归人 2021-01-19 08:02

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];

3条回答
  •  借酒劲吻你
    2021-01-19 08:17

    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);
    });

提交回复
热议问题