javascript - 尝试在表格中显示数组的内容时,顺序颠倒
问题描述
我是编码方面的初学者,尤其是 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 = ""; 的原因 使用数组时需要。
谢谢您的帮助。
解决方案
首先,您的代码正在生成看起来像这样的东西
<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>
推荐阅读
- neo4j - 如何将查询结果存储在列表中并稍后在 neo4j 中使用
- matplotlib - 底图圆形立体图地图边界裁剪
- kotlin - Corda Custom Notary 教程问题
- rest - 发出 HTTPS API 请求时的安全问题
- python - sphinx 删除自动模块中 args 的模块前缀
- c# - 如何使这个控制器的类和构造函数可重用?
- go - 如何在没有隐式缓冲区的情况下将值从一个 Go 通道传输到另一个通道?
- python - Statsmodel 拦截与 Seaborn lmplot 拦截不同
- php - 查询邮件和php邮件功能
- javascript - 在滚动时,粒子未指向正确的点