0

Possible Duplicate:
Convert string to variable name in Javascript

I have different variables (var1, var2, var3,.., to var10). I want to update them using a for loop like this:

for(var i=0; i<10;i++){
 var+i = i+20;
}

To obtain something like this:

var1 = 21;
var2 = 22;
var3 = 23;
...
var10 = 30;

My issue consists I can't concatenate the name of the variable with its id/position. Any suggestions?

Community
  • 1
  • 1
DGM.-
  • 151
  • 3
  • 13

2 Answers2

6

Use Array instead of variables.

Live Demo

arr = []
for(var i=0; i<10;i++){
 arr[i] = i+20;
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Adil
  • 146,340
  • 25
  • 209
  • 204
2

Global variables (if that's what they are) are properties of the window object so you could do something like this:

for(var i=0; i<10;i++){
    window["var"+i] = i+20;
}

Of course, I would recommend you use a different and simpler approach: arrays!

var data = [];
for(var i=0; i<10;i++){
    data[i] = i+20;
}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360