Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2010
    Thanked 0 Times in 0 Posts

    Question Initializing x amount of variables

    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; ?


  • #2
    New Coder
    Join Date
    May 2010
    Thanked 0 Times in 0 Posts
    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
    Last edited by swieder; 07-19-2010 at 05:55 PM.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,747 Times in 4,709 Posts
    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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    jomak73 (07-20-2010)


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts