Javascript Eval vs IF语句(许多IF语句)

Javascript Eval vs IF语句(许多IF语句),javascript,eval,Javascript,Eval,这把小提琴很好地解释了我在找什么。我正在试图找到一种最简单的方法来编写代码,而不必使用eval。我可以不用eval就完成它,但我想我必须编写1000条IF语句。还是有别的办法 HTML 另一种方法是重写当前通过点表示法访问的用法,并改用括号表示法 launch_no_eval:function(id) { //we init a blank dhtmlxwindow and do some other things here, then... if (id===

这把小提琴很好地解释了我在找什么。我正在试图找到一种最简单的方法来编写代码,而不必使用
eval
。我可以不用
eval
就完成它,但我想我必须编写1000条IF语句。还是有别的办法

HTML


另一种方法是重写当前通过
点表示法
访问的用法,并改用
括号表示法

launch_no_eval:function(id) {
        //we init a blank dhtmlxwindow and do some other things here, then...
        if (id==="window_a") var x = wins.a({x:1}); //fill dhtmlxwindow with proper content
        else if (id==="window_b") var x = wins.b({x:1}); //fill dhtmlxwindow with proper content
        else if (id==="window_c") var x = wins.c({x:1}); //fill dhtmlxwindow with proper content
        //and so on for literally thousands of items.
    }
可以改写如下:

launch_no_eval:function(id) { 
        var x = wins[id]({x:1});
}
这意味着您的HTML标记可以从

<a href="javascript:core.launch_no_eval('window_a');">Window-A</a><br>
<a href="javascript:core.launch_no_eval('window_b');">Window-B</a><br>
<a href="javascript:core.launch_no_eval('window_c');">Window-C</a><br><br>

为什么不使用带参数的函数呢?或者某种对象映射?我无法控制链接。它们实际上不是链接,而是DHTMLX工具栏。我只能为ID提供一个字符串。因此我使用实际的函数名/调用作为ID,然后对其进行
eval
ing。您应该在此处发布代码。小提琴是最好的选择。看到了吗?你可以传递你想要的任何东西吗?不太确定你想要实现什么,但是
赢了。a({x:1}
赢了['a']({x:1})
,所以这个函数可以写成:
funcname:function(id){var x=win[id]({x:1}}
,然后你可以传递个人id(即
a
b
,等等)它更像是
wins[id.replace('window_','')({x:1})
@DanielWeiner Correct。假设HTML不能更改为在
窗口\u id
字符串中传递唯一id。这就是我要找的!谢谢是的,我可以做任何我想要的ID,所以替换工作或更简单的a,b,c工作。谢谢各位。忘记那样引用对象了。呃。请记住:几乎没有必要使用
eval()
eval()
是邪恶的。
launch_no_eval:function(id) { 
        var x = wins[id]({x:1});
}
<a href="javascript:core.launch_no_eval('window_a');">Window-A</a><br>
<a href="javascript:core.launch_no_eval('window_b');">Window-B</a><br>
<a href="javascript:core.launch_no_eval('window_c');">Window-C</a><br><br>
<a href="javascript:core.launch_no_eval('a');">Window-A</a><br>
<a href="javascript:core.launch_no_eval('b');">Window-B</a><br>
<a href="javascript:core.launch_no_eval('c');">Window-C</a><br><br>
launch_no_eval:function(id) {
        // replace 'window_' with empty string to retrieve unique id
        var x = wins[id.replace('window_', '')]({x:1});
}