www.webdeveloper.com
Results 1 to 3 of 3

Thread: dynamic variable declarations ?

  1. #1
    Join Date
    Mar 2011
    Posts
    43

    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
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    It depends on. If you intend to use global variables, that is simple: global variables are properties of the super global object: window
    Code:
    for (var x = 0; x < 5; x++) {
     window['text'+x]= 500;
    }
    If you need them to have a private scope, maybe it will be better to use an Object, and make those "variables" to be properties of that object;
    Code:
    var myObject={}
    for (var x = 0; x < 5; x++) {
    myObject['text'+x]=500;
    }
    //test:
    alert(myObject['text1']);
    or:
    Code:
    function Constructor(){
    for (var x = 0; x < 5; x++) {
    this['text'+x]=500;
    }
    }
    var myObject=new Constructor();
    //test:
    alert(myObject['text1']);

  3. #3
    Join Date
    Aug 2007
    Posts
    3,767
    Or, in this case, you shouldn't have variables test0 to test4, but an array test with 5 elements.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles