包含可执行函数代码的字符串 [英] String containing code to executable function
问题描述
$ b
var code =function Solve(args){/ /做东西并返回值};;
转换为可传递参数的可执行函数。
当我将它与 eval(code +Solve(args););
一起使用时,它没有给出任何错误,但结果与预期不符。我也试过:
var fu = eval(code);
var result = fu(args);
fu未定义。
我做错了什么,或者有更好的方法来做到这一点。
使用eval通常是一种非常糟糕的做事方式。
$ b eval将把代码放到全局命名空间中
var code =function Solve(args){return args * 2};
eval(code);
var val = 1;
var result = Solve(val);
如果您不知道名称,则必须执行此类操作。
var code =function Solve2(args){return args * 2};
var val = 3;
var result = eval((+ code +)(+ val +););
上述方法的问题是它会使用toString()
使用 new Function
var sumCode =return a + b;
var sum = new函数(a,b,sumCode);
sum(1,2);
I basically want to convert a string containing code like this -
var code = "function Solve(args) { // do stuff and return value};";
into an executable function which you can pass arguments.
When I use it with eval(code + "Solve(args);");
It gives me no errors but the results are not as expected. I also tried:
var fu = eval(code);
var result = fu(args);
fu stays undefined. Am I doing something wrong or is there a better way to do this.
Using eval is normally a very bad way of doing things.
eval is going to put the code into the Global namespace
var code = "function Solve(args) { return args * 2}";
eval(code);
var val = 1;
var result = Solve(val);
if you do not know the name, you would have to do something like this
var code = "function Solve2(args) { return args * 2}";
var val = 3;
var result = eval("(" + code + ")(" + val + ");");
problem with the above method is it will use toString()
A better way to make a function from a string is using new Function
var sumCode = "return a + b";
var sum = new Function("a","b", sumCode);
sum(1,2);
这篇关于包含可执行函数代码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!