首页 > 解决方案 > 尝试在表格中显示数组的内容时,顺序颠倒

问题描述

我是编码方面的初学者,尤其是 JavaScript 方面的初学者。我的作业告诉我使用array.map()添加索引的 HTML 表格中显示内容。

var txt = "";
var products = ["one", "two", "three", "four", "five"];
var products2 = products.map(withIndex);

document.getElementById("demo").innerHTML = txt;

function withIndex(value, index, array) {
    txt = ("<tr><td>") + (index+1) + " " + value + txt + ("</tr></td>");
}
<table id="demo"></table>

这几乎可以正常工作,但表格的内容以相反的顺序显示,例如:5 五 4 四 3 三 2 二 1 一

我也不完全理解 var txt = ""; 的原因 使用数组时需要。

谢谢您的帮助。

标签: javascripthtml

解决方案


首先,您的代码正在生成看起来像这样的东西

<tr><td><tr><td><tr><td></tr></td></tr></td></tr></td>

您将以前的代码放在新代码之后,但您也将它放在新的 td 中。

您使用的地图完全错误。

var txt = "";
var products = ["one", "two", "three", "four", "five"];
var products2 = products.map(withIndex);

document.getElementById("demo").innerHTML = products2.join("");

function withIndex(value, index, array) {
    return "<tr><td>" + (index+1) + " " + value + "</td></tr>";
}
<table id="demo"></table>

要按照您的方式进行操作,您需要使用 forEach

var txt = "";
function withIndex(value, index, array) {
  txt = txt + "<tr><td>" + (index+1) + " " + value + "</tr></td>";
}

var products = ["one", "two", "three", "four", "five"];
var products2 = products.forEach(withIndex);

document.getElementById("demo").innerHTML = txt;
<table id="demo"></table>


推荐阅读