我的问题是如何做到这一点,但我遇到了eval
似乎工作.我被告知eval
是邪恶的,为什么解释为什么我的头脑,所以我的问题是:
使用eval
这样或其他方法完全没有问题吗?
var condition1=false;
var condition2=true;
var condition3=false;
//etc
if (condition1){x = "1"}
else if (condition2){x = "2"}
else if (condition3){x = "3"};
//etc
var thing1= 11;
var thing2= 22;
var thing3= 33;
//etc
eval ("thing" + x)
Run Code Online (Sandbox Code Playgroud)
可能最好的解决方案是用数组替换所有这些变量:
thing = [11, 22, 33 ...];
Run Code Online (Sandbox Code Playgroud)
那么你可以这样做:
thing[x]; // either change your code to zero indexed or subtract 1 here
Run Code Online (Sandbox Code Playgroud)
如果变量是全局变量,您也可以这样做:
window["thing"+x];
Run Code Online (Sandbox Code Playgroud)
但理想情况下,你不希望这些是全球性的.
归档时间: |
|
查看次数: |
75 次 |
最近记录: |