简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM