[英]How do I do “eval” on a string containing a function
In the following example, I would expect b
and c = eval(a)
to contain the same function, one that always returns true.在以下示例中,我希望
b
和c = eval(a)
包含相同的 function,始终返回 true。 However, a
does not get evaluated, it rather throws a syntax error: Uncaught SyntaxError: Function statements require a function name
.但是,
a
没有得到评估,而是引发语法错误: Uncaught SyntaxError: Function statements require a function name
。 However, if if name the function, c
contains undefined
.但是,如果命名 function,
c
包含undefined
。
var a = "function() { return true }";
var b = function() { return true };
var c = eval(a);
console.log(b,c);
The problem is that the code you're feeding into eval
is being evaluated where a statement is expected, but the code you have after var b =
is being evaluated as an expression.问题在于,您输入
eval
的代码正在被预期语句的地方评估,但您在var b =
之后的代码被评估为表达式。 When the parser is expecting a statement, the function
keyword starts a function declaration , which requires a name.当解析器期待一个语句时,
function
关键字开始一个 function声明,它需要一个名称。 But where an expression is expected, the function
keyword starts a function expression , in which a name is optional.但是在需要表达式的地方,
function
关键字会启动一个 function表达式,其中名称是可选的。
To make your eval
work on an expression instead, surround the code with (
and )
:要使您的
eval
改为在表达式上工作,请使用(
和)
将代码括起来:
var a = "function() { return true }"; var b = function() { return true }; var c = eval("(" + a + ")"); // −−−−−−−−−−^^^^^−−−^^^^^ console.log(b,c);
Warning : Be very careful using eval
and avoid using it if possible.警告:使用
eval
时要非常小心,并尽可能避免使用它。 Its purpose is to execute arbitrary code from strings.它的目的是从字符串执行任意代码。 If you use it, you must trust that the source of that string is trustworthy.
如果您使用它,您必须相信该字符串的来源是可信赖的。 Never take user input from user A and then
eval
it in a session for user B unless user B is fully aware of what's going on (for instance, as with the Stack Snippet above — I'm user A, you're user B; presumably if you click the Run button, you realize code will get run).永远不要从用户 A 获取用户输入,然后在用户 B 的
eval
中对其进行评估,除非用户 B 完全知道发生了什么(例如,与上面的堆栈片段一样——我是用户 A,你是用户 B;大概如果您单击“运行”按钮,您将意识到代码将运行)。 In fact, when dealing with non-programmers, don't even eval code from user A in user A's session.事实上,在与非程序员打交道时,甚至不要在用户 A 的 session 中评估来自用户 A 的代码。 :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.