View Full Version : Initializing x amount of variables

07-19-2010, 05:45 PM
This is probably a really simple question. Is it possible to initialize x amount of variables. Like someone enters 10 into an input box and it makes 10 variables called variable1, variable2, variable3, etc.
How would you name them?
variable + num = 0; ?


07-19-2010, 05:50 PM
Sounds like you need a loop. Something like this?

edit: make sure you define your variable

var x;
for(x=1; x=(variable with number of input by user); x++)
document.write("variable" + x);

This says, start at with x at one; continue until x = input; increment up


variable1,variable2,varible3... etc

This simply writes it out, you could certainly have the loop define variables instead of document.write

Old Pedant
07-19-2010, 09:17 PM
I disagree with swieder.

Heard of arrays?? Use them!

If the user needs 10 values, just create an array with 10 elements.

If you create 10 named variables, then you have the problem of *accessing* them. You can create them dynamically, with mild pain, but then every time you need one of them you have to *access* it dynamically, because you won't know for sure that a given variable exists!!

Using an array eliminates all this work and problems.

It's easy to create an array of any size:

var n = parseInt( prompt("How many elements do you want?") );
var myVariable = new Array(n);

And it's easy to find how many elements are in the array:

var howMany = myVariable.length;

You'll have to work hard to convince me that creating and maintaining separate variables is a good idea, at all.