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!
CodePudding user response:
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
CodePudding user response:
You can try to use globalThis or window.
function nameFunction(name, f) {
return {
[name](...args) {
return f(...args)
}
}[name]
}
// use globalThis
for (let i = 1; i <= 3; i ) {
const funcName = `car${i}`;
const func =
nameFunction(funcName, () => console.log(`this is car ${i}`));
globalThis[funcName] = func;
}
car1(); car2(); car3();
// use window
for (let i = 4; i <= 6; i ) {
const funcName = `car${i}`;
const func =
nameFunction(funcName, () => console.log(`this is car ${i}`));
window[funcName] = func;
}
car4(); car5(); car6();
CodePudding user response:
I hope this link will help you with this problem.
Here they have discussed 2 ways of solving the problem. (One with "eval" and the other with "windows" object.