Search code examples
javascriptloopsvariableswhile-loopautomation

create a new variable automaticaly


This is a general question. But an answer in JavaScript would suit me the best. I'm searching for a way to create variables after a pattern automatically. For example, I want to create a while-loop in which a variable gets declared. In set loop, I want to create the variable car1. However, in the next loop pass I want to do the same thing BUT call the Variable car2 this time. I'll try to write it in pseudocode:


//this should happen in the first loop
while(true){
  var car1 = 1 + 2;
  console.log(car1)
}

//this should happen in the second loop
while(true){
  var car2 = 1 + 2;
  console.log(car)
}

//In both cases "3" should be the output. But different Variables

Contrary to this example. I want to do all this in a single while loop. And on every while loop, a new variable should be created. So car1,car2,car3,car4.

Thanks in advance!


Solution

  • Maybe you can use an array and add an item every loop iteration or a hash map with a naming convention you set for the keys