Home > Mobile >  equating last value in loop problem in innerHtml
equating last value in loop problem in innerHtml

Time:03-02

forecasts is array who has a 10 elements when ı try to print its work perfectly when ı use innerHtml its giving the last value of items and everything is look same

const getOtherDays = (data) => {
  data.forecasts.forEach((forecast)=>{
    for(var i = 0; i < day.length; i  ) {
      items = forecast.day;
      console.log(items)
      day[i].innerHTML = `${items}`
    }
    })
  }
  

CodePudding user response:

You shouldn't use a nested loop. If each element of data.forecasts is for a different day, use the index in that array to assign to the corresponding DOM element.

const getOtherDays = (data) => {
  data.forecasts.forEach((forecast, i) => {
    items = forecast.day;
    console.log(items)
    day[i].innerHTML = `${items}`
  })
}

CodePudding user response:

You are looping over the elements and setting it to the forecast of the day on every one. You want to select the specific element. The forEach index has the index. Hopefully that index matches the day in your elements. Basic idea:

const getOtherDays = (data) => {
  data.forecasts.forEach((forecast, index)=>{
    items = forecast.day;
    day[index].innerHTML = `${items}`;
  })
}
  • Related