简体   繁体   中英

Javascript: Creating a Table from an Array

I have an HTML Table:

<table> <tr id="0"></tr> <tr id="1"></tr> <tr id="2"></tr> <tr id="3"></tr> </table>

I then make an array of 16 numbers, shuffle the array, and then add one cell per number in Javascript.

var numbers = shuffle([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8]);
console.log(numbers)

function shuffle(o) {
            for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
            return o;
}
function addCell(row, number) {
            var cell = document.getElementById(row).insertCell(0)
            cell.innerHTML = number;
}
function setNumbers() {
    var column = 0;
    var row = 0;
    for (i = 0; i <= numbers.length; i++) {
        column = column + 1;
        if (column > 4) {
            column = 0;
            row = row + 1;
        }
        console.log(row)
        addCell(row, numbers[i]);
    }
}
setNumbers()

The function setNumbers() should create a table with 4 rows and 4 columns. It should create something like this:

5 7 6 2
1 4 3 4
8 3 2 1
5 6 7 8

However, it creates this:

8   5   1   5
6   2   4   6   4
7   2   8   3   1
undefined   3   7

Four numbers in row 1,

Five numbers in rows 2 and 3,

and 2 numbers and an undefined in row 4

There is a minor bug in the handling of the value of column , since you are checking column > 4 from the second loop onward the row will have 5 items

 var numbers = shuffle([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8]); console.log(numbers.length, numbers) function shuffle(o) { for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } function addCell(row, number) { var cell = document.getElementById(row).insertCell(0) cell.innerHTML = number; } function setNumbers() { var column = 0; var row = 0; for (i = 0; i < numbers.length; i++) { addCell(row, numbers[i]); if (column == 3) { column = 0; row = row + 1; } else { column++; } } } setNumbers() 
 <table> <tr id="0"></tr> <tr id="1"></tr> <tr id="2"></tr> <tr id="3"></tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM