简体   繁体   中英

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();

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();

You can just add 1 with {i}

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();

console.log( ${arr[i]} in ${i+1} days )

const arr = [17,21,23];
const printForecase = ()=>{
        let days = 1;
        for(let newarr of arr){
           console.log(`${newarr} in ${ days++ } Days`)
        }
}

printForecase()
  1. Add 1 to the embedded expression ${i} so that it is ${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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM