Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a variable dynamically in javascript

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

like image 243
Chris Bier Avatar asked Sep 30 '10 20:09

Chris Bier


1 Answers

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];
like image 184
Dan Davies Brackett Avatar answered Oct 11 '22 01:10

Dan Davies Brackett