Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New to the CF scene
    Join Date
    Dec 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Defining a variable with another variable

    Hi all!

    I've just started with programming in javascript, and I've run into a problem that I haven't been able to find an answer to in any books or on the web. I was hoping someone could help.

    I've been trying to call a variable so that I can set it equal to something by using another variable's value as part of the name. Something like this:

    var test1 = "blah";
    var i = 1;

    test+i = "It Worked";

    Now if this worked the way that I wanted, then test1 would now contain the phrase "It Worked." Does anyone know what I can do to make this work? I've tried reading up on this and I cannot find a way to do this. I hope someone can help.

    Thanks!

  • #2
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    Arrays are what you are looking for:

    Code:
    var test = []; // or... var test = new Array();
    var i = 1;
    
    test[i] = "It Worked";
    
    alert(test[1]);
    Trinithis

  • #3
    New to the CF scene
    Join Date
    Dec 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    actually, i cannot use an array to do what i need to do, i was curious if what i put up before was possible. I know it must be but i'm just not sure how to do it.

    thanks for trying to help though

  • #4
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    You want to do reflection?

    Code:
    var test1 = "blah";
    var i = 1;
    
    window["test"+i] = "It Worked";
    
    alert(test1);
    Trinithis

  • #5
    New to the CF scene
    Join Date
    Dec 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    awesome that worked! i didn't know it was called a reflection. thanks man.

  • #6
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    Glad that was what you had wanted.

    If you want to read up more on reflection:
    http://en.wikipedia.org/wiki/Reflect...puter_science)

    In particular, here's a JS example:
    http://en.wikipedia.org/wiki/Reflect...8JavaScript.29
    Trinithis


  •  

    Posting Permissions

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