How to reference a variable dynamically in javascript

﹥>﹥吖頭↗ 提交于 2019-11-29 20:02:58

问题


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


回答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];



回答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];



回答3:


How about:

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



回答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();



回答5:


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

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




回答6:


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)]; 
         } 



回答7:


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



来源:https://stackoverflow.com/questions/3834373/how-to-reference-a-variable-dynamically-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!