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?

3

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

you can use the square bracket syntax on any object.
@Alnitak - I didnt say you couldn't! I just used window as the example.
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] = ...;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.