Reputation: 16163
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?
Upvotes: 2
Views: 12925
Reputation: 19
Try this:
var counter = 1;
while(counter < 4) {
eval('name' + counter + ' = ' + counter);
counter++;
}
alert(name1);
Upvotes: -1
Reputation: 104760
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 comma 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)
Upvotes: 1
Reputation: 5335
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 ) ;
Upvotes: 0
Reputation: 838086
You'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.
Upvotes: 4
Reputation: 523214
Use an array.
Suppose you're running in a browser and the nameXXX
are global variables, use
window["name" + counter] = 5;
Upvotes: 2
Reputation: 25249
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']);
Upvotes: 2
Reputation: 342323
You can use associative arrays,
var mycount=new Array();
var count=1;
while (count < 4) {
mycount[count++]=5;
}
Upvotes: 2