0

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);
boatus
  • 55
  • 4
  • 1
    when you are looking at the last element in the array, `arr[i+1]` is `undefined` (because `i+1` is after the end of the array). And as there is no `undefined` in your array, the result of `indexOf(undefined)` returns `-1` – derpirscher Aug 10 '21 at 10:35
  • Thanks. Yes I had thought about that and I tried to fix it by writing ${arr.indexOf(arr[i] + 1)} so that the + 1 would be outside of the array, but doing that none of the code works. – boatus Aug 10 '21 at 10:42
  • Actually, I don't know, why you would need the `indexOf` anyways ... because `arr.indexOf(arr[i+1])` is -- per definition -- always `i +1` (unless `i+1` is not out of bounds). Just use `console.log(\`${arr[i]}° in ${i + 1} days ...\`);` – derpirscher Aug 10 '21 at 10:45
  • 1
    @derpirscher It's not always i+1 if duplicate values exist in array – charlietfl Aug 10 '21 at 11:24

1 Answers1

2

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.

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
  • Thanks, your method works and is even cleaner. But I don't understand why it works. The variable i indicates the values of the array, so i should be 12, 5, -5, 0 and 4. So why ${i+1} gives the index of the value +1? Shouldn't it give 13, 6, -4, 1 and 5? – boatus Aug 10 '21 at 10:45
  • No you are wrong, `i` indicates the progressive number, `arr2[i]` is the value of array at index `i` (for example `arr2[0] = 12`), take a look [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration?retiredLocale=en) – Simone Rossaini Aug 10 '21 at 10:48