【发布时间】:2021-03-31 07:30:38
【问题描述】:
我正在遍历数组“fruits”。我希望它的索引从 1 开始。但输出从 0 开始。 这是我的代码
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
这是输出。
0:apple
1:orange
2:cherry
如何让它从 1 开始?
【问题讨论】:
-
试试
var fruits = [null,"apple", "orange", "cherry"]; -
forEach 从0开始索引,需要在innerHTML中手动增加索引值。 (index+1) + ":" + ...
-
“我如何让它以 0 开头?” - 它已经做到了?
-
所以加一个??????
标签: javascript node.js reactjs foreach