Skip to content
Advertisement

How to start item index with 1

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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement