How to reference a variable dynamically in javascript
Asked Answered
M

8

9

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!!

Missis answered 30/9, 2010 at 20:2 Comment(0)
C
10

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];
Ciliata answered 30/9, 2010 at 20:6 Comment(1)
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.Caning
R
5

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];
Rumba answered 30/9, 2010 at 20:5 Comment(0)
V
4

How about:

var dataString = dataString + eval('amtgc1' + step);
Varia answered 30/9, 2010 at 20:6 Comment(8)
this will work, but eval is evil and should be avoided when a switch to array or object-literal syntax will suffice.Ciliata
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!Missis
@DDaviesBrackett - and what do you think jQuery uses internally? ;-)Varia
@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.Ciliata
@Jakub yes, jQ does use eval, but not as a way to avoid using arrays!Ciliata
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!Missis
@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.Varia
Using eval() definitely hinders the optimizations available to the runtime, and should therefore always be considered a performance problem.Darrondarrow
T
1

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();
Tonetic answered 17/1, 2018 at 18:53 Comment(0)
I
0

Not tested, but can't see why you can't do this...

$('#amtgc1' + step).whatever();

Insurrection answered 30/9, 2010 at 20:6 Comment(1)
Only if the variables are dom elements with IDs.Desultory
S
0

If your amtgc1* variables are defined as a property of an object, you can reference them by name. Assuming they are declared in the global scope, they will be members of the window object.

        var inc=7; 
        var step=0; 
        while(step < inc){ 
            var dataString = dataString + window['amtgc1'+(step+1)]; 
            var step = step+1; 
        } 

If they are defined in a different scope (within a function) but not belonging to any other object, you're stuck with eval, which is generally considered bad.

also, hooray for loops!

        var inc=7; 
        for ( var step=0; step < inc; step++ ){ 
            var dataString = dataString + window['amtgc1'+(step+1)]; 
         } 
Sapphira answered 30/9, 2010 at 20:11 Comment(0)
E
0

I have built a way which you could solve this problem using objects to store the key values, where the key would be the reference to the task and the value will be the action (function) and you could use an if inside the loop to check the current task and trigger actions.

If you would like to compare dynamically concatenating strings with "variable", you should use the eval() function.

/* store all tasks references in a key value, where key will be
*  the task reference and value will be action that the task will 
*  Execute
*/
var storeAllTasksRefer = {

    amtgc11:function(){ alert("executing task amtgc11"); },
    amtgc112:function(){ alert("executing task amtgc112"); },
    "amtgc1123":"amtgc1123"
    // add more tasks here...

};

var inc = 7;
var step = 1;
var dataString = 'amtgc1';

while(step <= inc){

     var dataString = dataString + step;
     //alert(dataString); // check its name;
     step = step+1;

     // check if it is my var
    if( dataString  == 'amtgc112' ){

         // here I will reference my task
         storeAllTasksRefer.amtgc112();             


     }// end if

     /* you can also compare dynamically using the eval() function */
     if('amtgc1123' == eval('storeAllTasksRefer.'+dataString)){

        alert("This is my task: "+ eval('storeAllTasksRefer.'+dataString));

     } // end this if

} // end while

Here is the live example: http://jsfiddle.net/danhdds/e757v8ph/

eval() function reference: http://www.w3schools.com/jsref/jsref_eval.asp

Eloign answered 7/2, 2015 at 14:53 Comment(0)
G
0

Also if you are using web components and utilize JS classes then you can retrieve a variable (field) dynamically by his name as 'this' is an object:

testVar = 'test';

let varName = 'testVar';

console.log(this[varName]);
Gramme answered 16/2 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.