如何在javascript中动态引用变量 [英] How to reference a variable dynamically in javascript
问题描述
我试图在javascript中动态引用变量
I am trying to reference a variable dynamically in javascript
我要调用的变量是amtgc1#(其中#从1-7变化)
The variable I am trying to call is amtgc1# (where # varies from 1-7)
我使用while语句循环,而while语句中计数变量的值对应于我试图调用的变量的最后一位数。
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.
例如:
var inc=3;
var step=0;
while(step < inc){
var dataString = dataString + amtgc1#;
var step = step+1;
}
其中#基于变量step的值。我该怎么做呢?任何帮助表示赞赏!谢谢!!
Where # is based on the value of the variable "step". How do I go about doing this? Any help is appreciated! Thanks!!
推荐答案
而不是定义 amtgc1 [1-7]
作为7个不同的变量,将它们实例化为数组。所以你的服务器代码会发出:
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];
这篇关于如何在javascript中动态引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!