在for循环JavaScript中的每10个td之后中断行

时间:2019-03-12 11:35:39

标签: javascript loops for-loop

我想在数组中的每个第十个元素之后中断。如何在当前for循环内创建它?

function printa() {
    document.write('<table>');
    document.write('<tr>');
    for (var i = 0; i < numbers.length; i++) {
        document.write("<td>" + numbers[i] + "</td>");
    }
    document.write('<tr>');
    document.write('</table>');
}

下面显示的是输出: enter image description here

我想要的输出:

enter image description here

4 个答案:

答案 0 :(得分:1)

function genTable(values, rowLength = 10) {
  let content = ''

  for(let i = 0; i < values.length; i += rowLength) {
    const tds = values.slice(i, i + rowLength).map(value => `<td>${value}</td>`)
    content += `<tr>${tds.join("")}</tr>`
  }

  return `<table>${content}</table>`
}

const numbers = new Array(30).fill().map((_,i) => i+1)
const table = genTable(numbers)

console.log(table)
document.write(table);

答案 1 :(得分:0)

您可以添加if来检查所需条件。您不应该使用document.write ..

function printa() {
    document.write('<table>');
    document.write('<tr>');
    for (var i = 0; i < numbers.length; i++) {
        if (i != 0 && i % 10 == 0 && i != numbers.length-1) {
            document.write('</tr>');
            document.write('<tr>');
        }
        document.write("<td>" + numbers[i] + "</td>");
    }
    document.write('</tr>');
    document.write('</table>');
}

答案 2 :(得分:0)

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];

function tableCreate() {
  var body = document.getElementById('myTable');
  var tbl = document.createElement('table');
  tbl.style.width = '100%';
  tbl.setAttribute('border', '1');
  var trNum = Math.ceil(arr.length / 10);

  var arrNum = 0;
  for (i = 0; i < trNum; i++) {
    var tr = document.createElement('tr');
    for (j = 0; j < 10; j++) {
      var td = document.createElement('td');
      td.appendChild(document.createTextNode(arr[arrNum]))
      tr.appendChild(td)
      arrNum++;
    }
    tbl.appendChild(tr)
    console.log(trNum,i);
  }
  body.appendChild(tbl)
}
tableCreate();
<div id="myTable"></div>

答案 3 :(得分:-1)

我们可以将数据转换为简单的2d数组以使用如下所示的逻辑,

function printa(numbers) {
    document.write('<table>');
    for (var i = 0; i < numbers.length; i++) {
    document.write('<tr>');
    numbers2 = numbers[i]
    for (var j = 0; j < numbers2.length; j++) {
        document.write("<td>" + numbers2[j] + "</td>");
    }

    document.write('</tr>');
    }
    document.write('</table>');
}

 printa([[1,2,3,4,5,6,22,3,45,23],[34,45,5677,12,34,23,11,22,67,23],[657,765,657,567,567,56,2,6,66,78]])