I am running a loop, and I am trying to create a variable each time the loop runs with the number of the counter appended to the end of the variable name.
Here's my code:
var counter = 1;
while(counter < 4) {
var name+counter = 5;
counter++;
}
So after the loop runs there should be 3 variables named name1, name2, and name3. How can I append the counter number to the end of the variable I am creating in the loop?
I am running a loop, and I am trying to create a variable each time the loop runs with the number of the counter appended to the end of the variable name.
Here's my code:
var counter = 1;
while(counter < 4) {
var name+counter = 5;
counter++;
}
So after the loop runs there should be 3 variables named name1, name2, and name3. How can I append the counter number to the end of the variable I am creating in the loop?
Share Improve this question edited Mar 6, 2010 at 15:39 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Mar 6, 2010 at 8:17 zeckdudezeckdude 16.2k44 gold badges146 silver badges194 bronze badges8 Answers
Reset to default 4You're looking for an array:
var names = Array();
// ...
names[counter] = 5;
Then you will get three variables called names[0], names[1] and names[2]. Note that it is traditional to start with 0 not 1.
You can use associative arrays,
var mycount=new Array();
var count=1;
while (count < 4) {
mycount[count++]=5;
}
var counter = 1,
obj = {};
while ( counter < 4 )
obj['name'+counter++] = 5;
// obj now looks like this
obj {
name1: 5,
name2: 5,
name3: 5
}
// the values may now be accessed either way
alert(obj.name1) && alert(obj['name2']);
Use an array.
Suppose you're running in a browser and the nameXXX
are global variables, use
window["name" + counter] = 5;
If you use eval, don't use it inside the loop, but use the loop to build up a single string you can run the eval on once.
var counter= 1, name= 'name', evlstring= 'var ';
while(counter < 5){
evlstring+= name+counter+'=5,';
++counter;
}
evlstring= evlstring.slice(0, -1);
// trailing ma would throw an error from eval
eval(evlstring);
alert(name3);
I don't really trust the future of eval- it is really hard to optimize those nifty new javascript engines with eval, and I'm sure those programmers would like to see it die, or at least get it's scope clipped.
If you insist on global variables you could do this:
var counter= 1, name= 'name';
while(counter < 5){
window[name+counter]=5;
++counter;
}
alert(name3)
Use eval function , it will make the things
Example code, it will create the name1 ,name2 , name3 variables.
var count=1;
while ( count < 4 )
{
eval("var name" + count + "=5;");
count++;
}
alert ( name1 ) ;
alert ( name2 ) ;
alert ( name3 ) ;
Try this:
var counter = 1;
while(counter < 4) {
eval('name' + counter + ' = ' + counter);
counter++;
}
alert(name1);