Skip to content
Advertisement

Array print element index 0 as index 1

How can I print the output as

17 in 1 days

21 in 2 days

23 in 3 days

and not

17 in 0 days

21 in 1 days

23 in 2 days

const arr = [17, 21, 23];

const printForecase = function() {
    for (let i = 0; i < arr.length; i++) {
        console.log(`${arr[i]} in ${i} days`);
    } } 
printForecase();

Advertisement

Answer

Since the index starts from 0, you just need to add one (1) when you print it in your console.log() (${i+1})

const arr = [17, 21, 23];

const printForecase = function() {
    for (let i = 0; i < arr.length; i++) {
        console.log(`${arr[i]} in ${i+1} days`);
    } } 
printForecase();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement