使用eval调用稍微不同的函数名称的替代方法?

0 javascript

我的问题是如何做到这一点,但我遇到了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)

Jam*_*gne 5

可能最好的解决方案是用数组替换所有这些变量:

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)

但理想情况下,你不希望这些是全球性的.