SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2011
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    dynamic variable declarations ?

    Hi

    I want to be able to access variables by using strings. for example.

    Code:
    for (var x = 0; x < 5; x++) {
     "test" + x = 500;
    }
    would assign 500 to variables test0, test1, test2, test3, and test4. is it apossible somehow to accomplish this? perhaps using a library. Or maybe this code would actually work haha don't think so but never tried.

    thanks, geoff

  2. #2
    SitePoint Evangelist
    Join Date
    Jun 2007
    Location
    North Yorkshire, UK
    Posts
    483
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In this particular example if test were an array and x and index into the array you would have the same thing.

    No - "test" + x = 500 will not work.
    However - eval("test" + x + " = 500") will.

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    for (var x = 0; x < 5; x++) {
     window["test" + x] = 500;
    }
    console.log(test1);//500

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by gloosemo View Post
    I want to be able to access variables by using strings. for example.

    Code:
    for (var x = 0; x < 5; x++) {
     "test" + x = 500;
    }
    That is almost always never a good solution to the problem. Why can you not use an array to store the info?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

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