View Full Version : Initializing x amount of variables
07-19-2010, 04: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, 04:50 PM
Sounds like you need a loop. Something like this?
edit: make sure you define your variable
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
This simply writes it out, you could certainly have the loop define variables instead of document.write
07-19-2010, 08: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.
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.