【问题标题】:Using JS forEach to convert multi-dimensional array to html table使用JS forEach将多维数组转换为html表格
【发布时间】:2021-02-11 01:47:10
【问题描述】:

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

我在 forEach 中嵌套了一个 forEach 来构造行和单元格。但是,我不断在顶部收到两个“未定义”响应,每个团队一个。我认为它与 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>');
}

当我从行函数中删除对单元格函数的引用时,它会返回数组并且“未定义未定义”消失。请注意,我删除了“.forEach(cell)”并添加了数据标签。

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

Table without undefined at top

【问题讨论】:

  • 您正在使用&lt;/td&gt; 终止您的行,而不是&lt;/tr&gt;
  • 请阅读Why not upload images of code on SO when asking a questionedit 您的问题,将代码数据作为文本而不是图像。
  • 这不是 标签,我修复了它,它仍然是相同的输出。
  • 那么你目前的输出到底有什么问题?
  • 表格顶部的“未定义未定义”。它似乎是在行函数中创建的。

标签: javascript arrays foreach undefined


【解决方案1】:

我认为这会完成你想要的

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

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签