Search code examples
javascriptindexof

My indexOf() method works but when it comes to the last value, it stops working


I have an array with a set of temperatures: let arr2 = [12, 5, -5, 0, 4]. For each of these temperatures I want to write temperature + ° in 1 days, temperature 2 in 2 days etc. so I need to increase the number of the days and it has to start from 1, not from 0.

It works for all values of the array besides the last one. Why? In this example, the value of i is 4, so it should be 4+1 = 5, but instead of logging "in 5 days" it logs "in -1 days", so it clearly misses the last value.

What's my mistake?

let arr = [17, 21, 23];
let arr2 = [12, 5, -5, 0, 4];

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

printForecast(arr2);


Solution

  • Why don't use directly i + 1 like:

    let arr = [17, 21, 23];
    let arr2 = [12, 5, -5, 0, 4];
    
    const printForecast = function (arr) {
      for (let i = 0; i < arr.length; i++)
        console.log(`${arr[i]}° in ${i + 1} days ...`);
    };
    
    printForecast(arr2);

    You have this problem becuase the last arr[i + 1] is equal to arr[5], that index doesn't exist into your array.