1

Hi I need to create a load of variables in a javascript loop so say my loop goes round 5 times starting at 0 by the end of it the following variables should be defined:

variable_0
variable_1
variable_2
variable_3
variable_4

Can anyone tell me how to do this please?

geoffs3310
  • 5,599
  • 11
  • 51
  • 104
  • What will you be using the variables for? – Ja͢ck Jun 29 '12 at 10:08
  • Use an object or array for grouping stuff please :X also possible duplicate of [Javascript dynamic variable name](http://stackoverflow.com/q/5117127/995876) – Esailija Jun 29 '12 at 10:10
  • 1
    possible duplicate of [JavaScript: Get local variable dynamicly by name string](http://stackoverflow.com/questions/1920867/javascript-get-local-variable-dynamicly-by-name-string) – Florian Margaine Jun 29 '12 at 10:15

3 Answers3

4

This will create "global" variables by registering them on the window object:

for (var i = 0; i != 5; ++i) {
    window['variable_' + i] = null;
}

It's not really nice to do that though =/ a better way is to define an object in which you create dynamic properties.

var obj = {}
for (var i = 0; i != 5; ++i) {
    obj['variable_' + i] = null;
}

console.log(obj.variable_0); // null
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

Why not just use an array:

var variable = [];

If you really want to create 5 variables, you need to choose the scope of them, the easiest is probably window, then you can use the sqare bracket syntax:

for(var i=0;i<5; i++){
    window["variable_" + i] = 0; // or anything really!
}

Now the following variable is available:

window.variable_1 = 123
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You can only create variably named variables as part of an Object:

obj['variable_' + i] = value;

There's no equivalent for function scoped variables, although you can of course do:

function foo() {
    var obj = {};
    for (var i = 0; ... ) {
        obj['variable_' + i] = value;
    }
}

You can fake global variables (but shouldn't) by using the window global object in place of obj, as shown by @Jack.

Of course in most circumstances (and since you're using numbers to differentiate the variables) what you should really do is use an array:

var myvar = [];
for (var i = 0; i < n; ++i) {
    myvar[i] = ...;
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495