'How to assign a variable for each item of the loop

for (var i = 0; i < dataForecast.list.length; i += 8) {
  const data = dataForecast.list[i].dt_txt;
}

This loops gives out 5 intended looped pieces of data but I'm struggling to assign each loop to its own variable.



Solution 1:[1]

Use an array

const dataArr = [];
for (var i = 0; i < dataForecast.list.length; i += 8) {
  const data = dataForecast.list[i].dt_txt;
  dataArr.push(data);
}
console.log(dataArr); // access the array

Solution 2:[2]

It seems you want to dynamically generate and assign variable value. For this you can use eval() method like below:

dataArray = [1, 2, 3, 4, 5]
var x = 'data'

for (var i = 0; i < dataArray.length; i++) {
  eval('var ' + x + i + '= ' + dataArray[i] + ';');
}
console.log("data0=" + data0);
console.log("data1=" + data1);
console.log("data2=" + data2);
console.log("data3=" + data3);
console.log("data4=" + data4);

Note: It's not recommended to use eval() method due to security reasons. You can read more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Undo
Solution 2 PhoenixFrog