How to use number generated by FOR in the name of a variable?

4

How to use number generated by FOR in the name of a variable?

Example:

for (var i = 0; i < 5; i++) { 
var teste[i] = "teste é " +[i];
}

Example 2:

for (var b = 0; b < 5; b++) { 
var teste[b] = "teste";
}

OU

I have to create a group of numbered variables, for example:

var teste1
var teste2
var teste3...

What's the best way without being one by one?

    
asked by anonymous 15.06.2014 / 02:30

2 answers

5

Although possible , avoid creating variables with dynamic names!

In these examples, you may well use arrays, where each value can be obtained by the index.

When you say [i] , you are creating an array with i inside. If I understood the question well, you simply want the value i :

var teste = [];
for (var i = 0; i < 5; i++) { 
    teste[i] = "teste é " + i;
}

Notice that I've also changed its var teste[i] statement, which is a syntax error. Declare the array outside of the loop, and inside only assign each position. Another alternative is to use push :

var teste = [];
for (var i = 0; i < 5; i++) { 
    teste.push("teste é " + i);
}
    
15.06.2014 / 02:33
3

The bfavaretto response is most recommended, but in case you need to include the numeric index in the variable name for some reason, you can use any object (including the global object window ) and assign it new properties dynamically:

for (var i = 0; i < 5; i++) { 
    window["teste" + i] = "teste é " + i;
}
alert(teste3); // "teste é 3"

var testes = {};
for (var b = 0; b < 5; b++) { 
    testes["teste" + b] = "teste";
}
alert(testes.teste3); // "teste"

(in the case of assigning to window , it becomes a global, in the other case, you need to prefix with the created object; there are no means of creating a local variable in this way)

Note that is not a good practice , among other things because you can not iterate over your created variables easily (as you would if you used an array). I'm just responding literally to what was asked.

    
15.06.2014 / 03:43