views:

338

answers:

8

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?

+1  A: 

You can use associative arrays,

var mycount=new Array();
var count=1;
while (count < 4) {
   mycount[count++]=5;
}
ghostdog74
A: 

Use eval function , it will make the things

pavun_cool
+2  A: 
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']);
aefxx
+1  A: 

Use an array.


Suppose you're running in a browser and the nameXXX are global variables, use

window["name" + counter] = 5;
KennyTM
+2  A: 

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.

Mark Byers
A: 

Try this:

var counter = 1;

while(counter < 4) {
   eval('name' + counter + ' = ' + counter);
   counter++;
}

alert(name1);
A: 

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 ) ;
pavun_cool
A: 

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)
kennebec