嗨如果可能的话,从没有eval的字符串/数组运行javascript .这有点像我想要的.
code = ["document.write('hello')", "function(){}"];
code.run[1];
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,谢谢.
从字符串运行javascript的唯一方法是使用eval().
更正:除此之外eval("codeString");,new Function("codeString")();还将执行您的代码.这样做的缺点是,与您new Function(...)在预定义代码时可能使用的优化相比,您在调用时必须解释代码,如下例所示.
所以,eval("codeString");和new Function("codeString")();有可能的,但不好的想法.
更好的选择是将函数存储在数组中,如下所示:
function foo(){
document.write('hello');
}
function bar(){
return 1+2;
}
var code = [ foo,
function(){
alert("Hi there!");
},
bar
];
code[0](); // writes "hello" to the document.
code[1](); // alerts "Hi there!"
code[2](); // returns 3.
Run Code Online (Sandbox Code Playgroud)