使用JS forEach将多维数组转换为htmltable

Using JS forEach to convert multi-dimensional array to html table

我对 Javascript 数组的经验很少。我有一个足够复杂的需求,我需要将我的数据放入一个数组中,然后生成一个 HTML table。在这个例子中,我在这里有一个用于排行榜的多维数组,其中每个值都是团队分数的数组。

我在 forEach 中嵌套了一个 forEach 以构建行和单元格。但是,我一直在顶部收到两个 'undefined' 响应,每个团队一个。我认为它与forEach方法的thisValue部分有关,但我无法阻止或替换它。

我确定这不是设置它的正确方法,但如果现在可以通过一个小的调整让它工作,那将是理想的。查看图像。感谢您的帮助!

leaderBoard.forEach(row);

function row(value,index,array)
{
    document.write('<tr>' + value.forEach(cell) + '</tr>');
}

function cell(value,index,array)
{
    document.write('<td>' + value + '</td>');
}

当我从行函数中删除对单元格函数的引用时,returns 数组和 'undefinedundefined' 消失了。请注意,我删除了“.forEach(cell)”并添加了数据标签。

function row(value,index,array)
{
    document.write('<tr><td>' + value + '</td></tr>');
}

Table without undefined at top

我想这会完成你想要的

leaderBoard.forEach(function (row) {
  row.forEach(function (cell) {
      document.write('<tr><td>' + cell + '</td></tr>');
    });
});

您尝试删除对单元格函数的引用已结束。问题是您将整行写入 1 个单元格

//value = [AM, 90, 76, 67, 233]
function row(value,index,array)
{
    document.write('<tr><td>' + value + '</td></tr>');
}