问题
I am trying to create multiple new variables inside a loop. The number of new variables depends on the lenght of another variable (variable "list" used below).
for(var i = 0; i < list.lenght; i++)
{
var counter + i; // create new variable (i.e. counter1, counter2,...)
}
I found a lot of very simmilar questions on StackOverflow, and the answer is mostly using an array (i.e. How do I create dynamic variable names inside a loop?).
If I use the suggested solution, do I create an array of variables? So in my case I will create multiple counters and I can then add values to that variables, i.e.:
counter6++;
If that is not the case how could I tackle the problem?
I apologize for asking you to explain an old answer, but I cannot comment in the old one because of low reputation.
回答1:
You have some options here :
Create them global (not best practice ) :
for(var i = 0; i < list.lenght; i++){
window['counter' + i] = 0; // create counter1, counter2,...)
}
Use object :
var scope = {};
for(var i = 0; i < list.lenght; i++){
scope['counter' + i] = 0; // create scope.counter1, scope.counter2,...)
}
Use Object with with
keyword
var scope = {};
for(var i = 0; i < list.lenght; i++){
scope['counter' + i] = 0; // create scope.counter1, scope.counter2,...)
}
with(scope){
// here you can acesess keys in the scope object like them variable on the function scope
counter0++
}
Use plain old Array
var scope = new Array(list.length);
回答2:
You can create an object, set property names to expected variable names, then use object destructuring assignment to get the property assignment or index of an object having a .length
as a variable identifier; or use array destructuring to assign an identifier to a specfic index.
let [list, obj] = ["abc", {}];
for (let i = 0; i < list.length; i++) {
obj["counter" + i] = list[i]
}
let {counter0, counter1, counter2} = obj;
console.log(counter0, counter1, counter2);
Alternatively
let list = "abc";
let {0:counter0, 1:counter1, 2:counter2} = list;
console.log(counter0, counter1, counter2);
let list = ["a","b","c"];
let [counter0, counter1, counter2] = list;
console.log(counter0, counter1, counter2);
来源:https://stackoverflow.com/questions/42739214/create-multiple-variables-inside-for-loop