将3D数组输出为表格

时间:2015-09-05 07:37:35

标签: javascript arrays dom

我为作业制作了一个二十一点游戏,并为排行榜和卡片制作阵列。

我想像这样打印排行榜。卡片(在单个细胞中)| TOTAL。

帮助将不胜感激,谢谢

function makeTable(leaderBoard) {
    var table = document.createElement('table');
    for (var i = 0; i < leaderBoard.length; i++) {
        var row = document.createElement('tr');
        for (var j = 0; j < leaderBoard[i].length; j++) {
            var cell = document.createElement('td');
            cell.textContent = leaderBoard[i][j];
            row.appendChild(cell);
        }
        table.appendChild(row);
    }
    document.getElementById('leaderBoard').innerHTML = table;
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

也许示例输入的格式不正确,但是重用预定义的表和html表函数,例如insertRow和insertCell(不一定更好,但它们比createElement和append更容易看到):

<div id="leaderBoard"><table id=leaderTable></table></div>

function updateleaderboard(leaderBoard) {    
    var table = document.getElementById('leaderTable');
    while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any    
    for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
        var row =table.insertRow();
        var arrCards = leaderBoard[i++];
        var total = row.insertCell();
        total.className = 'res';
        total.textContent = leaderBoard[i];
        arrCards.forEach(function(c,ind){
            row.insertCell(ind).textContent = c;
        });
    }
}

var cards = [['Q','4','5'],19];

updateleaderboard(cards);

Fiddle