I’m iterating through array “fruits”. I want its index to start with 1. but the output starts at 0. Here is my code
var fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); function myFunction(item, index) { document.getElementById("demo").innerHTML += index + ":" + item + "<br>"; }
here is the output.
0:apple 1:orange 2:cherry
how do i make it to start with 1 ?
Advertisement
Answer
Manually add 1 to the index:
(index + 1)
var fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); function myFunction(item, index) { document.getElementById("demo").innerHTML += (index + 1) + ":" + item + "<br>"; }
<div id='demo'></div>