How to reference a variable dynamically in javascript

10,745

Solution 1

Rather than defining amtgc1[1-7] as 7 different variables, instantiate them as an array instead. So your server code would emit:

var amtgc1 = [<what used to be amtgc11>,<what used to be amtgc12>, ...insert the rest here...];

Then, you can refer to them in your loop using array syntax:

var dataString = dataString + amtgc1[step];

Solution 2

The only way you can do this (afaik) is to throw all of your amtgc1# vars in an object such as:

myVars = {
  amtgc1: 1234,
  amtgc2: 12345,
  amtgc3: 123456,
  amtgc4: 1234567
};

Then you can reference it like

myVars["amtgc" + step];

Solution 3

How about:

var dataString = dataString + eval('amtgc1' + step);

Solution 4

It is true that eval() is not always recommended, but that would work. Otherwise depending on the scope, you can reference most things like an object in JavaScript. That said, here are examples of what you can do.

Global scope

var MyGlobalVar = 'secret message';
var dynamicVarName = 'MyGlobalVar';
console.log(window.[dynamicVarName]);

Function Scope

function x() {
  this.df = 'secret';
  console.log(this['df']);
}
x();
Share:
10,745
Chris Bier
Author by

Chris Bier

Jesus is my life! Please read John chapter 3 in the Bible :) Web Developer &amp; Graphic Designer HTML, CSS, Javascript, PHP

Updated on July 24, 2022

Comments

  • Chris Bier
    Chris Bier almost 2 years

    I am trying to reference a variable dynamically in javascript

    The variable I am trying to call is amtgc1# (where # varies from 1-7)

    I am using a while statement to loop through, and the value of the counting variable in my while statement corresponds with the last digit of the variable I am trying to call.

    For Example:

                var inc=3;
                var step=0;
                while(step < inc){
                    var dataString = dataString + amtgc1#;
                    var step = step+1;
                }
    

    Where # is based on the value of the variable "step". How do I go about doing this? Any help is appreciated! Thanks!!

  • Patricia
    Patricia over 13 years
    i was just about to hit Post when the "5 billion new answers have been posted" popped up. this is pretty much what i was going to say.
  • Dan Davies Brackett
    Dan Davies Brackett over 13 years
    this will work, but eval is evil and should be avoided when a switch to array or object-literal syntax will suffice.
  • Chris Bier
    Chris Bier over 13 years
    This is the easiest way to do it and it works. I tried it just now it works perfectly. I don't have to change any of my existing code. Thanks Jakub!
  • Jakub Konecki
    Jakub Konecki over 13 years
    @DDaviesBrackett - and what do you think jQuery uses internally? ;-)
  • Dan Davies Brackett
    Dan Davies Brackett over 13 years
    @Chris B. Searching google for 'eval is evil' will give you lots of good hits on why it is. This is the first one: blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx essentially, eval leads to messy syntax that's hard to maintain and (because it nests an interpreter) extremely slow.
  • Dan Davies Brackett
    Dan Davies Brackett over 13 years
    @Jakub yes, jQ does use eval, but not as a way to avoid using arrays!
  • Chris Bier
    Chris Bier over 13 years
    I wish i could accept both, but in terms of cleanliness of syntax, I am going to have to go with DDavies. Thank you Jakub! I voted you up!
  • Jakub Konecki
    Jakub Konecki over 13 years
    @DDaviesBrackett - I do agree that one can misuse eval easily and it can lead to horrible code, but doing the eval I suggested won't lead IMHO to poor performance or hard to manage code.
  • Sean McMillan
    Sean McMillan over 13 years
    Only if the variables are dom elements with IDs.
  • Pointy
    Pointy about 10 years
    Using eval() definitely hinders the optimizations available to the runtime, and should therefore always be considered a performance problem.