Home > OS >  for loop only iterates one time
for loop only iterates one time

Time:07-14

I don't know why this code isn't looping.

It just gives me the first result which is 17°C in 1 day. What about the rest of the values in the array?

const temperatures = [17, 21, 23];
const forcasting = function (arr) {
  for (let i = 0; i <= arr.length; i  ) {
    let forCast = console.log(`${arr[i]}°C in ${i   1} day.`);
    return forCast;
  }
};
forcasting(temperatures);

CodePudding user response:

You are returning ‘forecast’ at the first iteration, it will cause the function to end (on any language and not only js), replace the return with print() and see the values.

CodePudding user response:

There are some issues with this code. 1st. It only loops once because you return in the first loop.

  • return ends the code running inside that function and returns forCast making forcasting equal to the return from the console.log()
  • just know returning in a loop will end it 2nd. Also for (let i = 0; i <= arr.length; i ) will try to access index 3 when the last index is actually 2. so it should be for (let i = 0; i < arr.length; i )

CodePudding user response:

you are using return before the loop ends. use this code:

const temperatures = [17, 21, 23];

const forcasting = function (arr) {
  let forCast = null;
  for (let i = 0; i <= arr.length; i  ) {
     forCast = console.log(`${arr[i]}°C in ${i   1} day.`);
  }
  return forCast;
};

forcasting(temperatures);

CodePudding user response:

Answer

No need to use return also your condition should be < not <=

Problems

You had your return inside the loop so it would stop after the first iteration

By having i<= arr.length it would try to make the loop stop when the index was 3 3 <= 3 but the index in JS starts at 0, so you are looking for the index 2 (3rd item) i < arr.legnth --> 2 < 3

const temperatures = [17, 21, 23];

const forcasting = arr => {
  for (let i = 0; i < arr.length; i  ) {
    console.log(`${arr[i]}°C in ${i   1} day.`);
    document.querySelector('section').innerHTML  = `<div>${arr[i]}°C in ${i   1} day.</div>`
  }
};
forcasting(temperatures);
<section></section>

  • Related