使用JavaScript从简单数组创建动态HTML表格

6
我希望能够用JavaScript编写一段代码,从一个仅包含数字的数组创建一个简单的HTML表格:
var array = [1,2,3,4,5,6,7,8,9,10];

表格应该长这样:
1 2 3 4 5
6 7 8 9 10

但是JavaScript代码应该根据数组大小动态变化(始终是5的倍数)。

我尝试了很多方法,但它从来没有按照我想要的方式工作。实现这个最简单的方法是什么?

这是我的一种尝试。

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

以及

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

这个例子只会显示数组中的两个值,但会重复很多次。

3
你好@Alexander-欢迎来到SO。你能展示一下你尝试过的代码吗? - itamar
1
@itamar 当然 - Alexander Hörl
3个回答

9
你可以遍历该数组,并在余数为5时构建新行。

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>


1

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

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

document.body.innerHTML = result;

请尝试一下,如果可以的话。

0

你可以尝试这样做,代码中有解释。不过需要注意的是,这段代码未经测试,可能需要进行一些调整。

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// start the table
var table = document.createElement("table");
var currentRow;
for (var i = 0; i < array.length; i++) {
  // put items in.
  var item = document.createElement("td");
  item.innerHTML = array[i];
  // if we are at the 
  if (i % 5 === 0) {
    // if it's not the first time you're creating row - first put the prev row into the table, then reassign it to a new table row.
    if (typeof currentRow !== 'undefined') table.appendChild(currentRow);
  currentRow.appendChild(item);

    currentRow = document.createElement("tr");
  }

}
// put the table into the body element, for example.
document.getElementsByTagName('body')[0].appendChild(table);

(1 % 5 === 0) 总是为假。 - Andrew Bone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接