Javascript 如何使用 js eval 返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7399024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use js eval to return a value?
提问by Radu094
I need to evaluate a custom function passed from the server as a string. It's all part of a complicated json I get, but anyway, I seem to be needing something along the lines:
我需要评估从服务器作为字符串传递的自定义函数。这都是我得到的复杂 json 的一部分,但无论如何,我似乎需要一些类似的东西:
var customJSfromServer = "return 2+2+2;"
var evalValue = eval(customJSfromServer);
alert(evalValue) ;// should be "6";
Obviously this is not working as I expected. Any way I can achieve this ?
显然,这不像我预期的那样工作。我有什么办法可以做到这一点?
回答by otakustay
The first method is to delete returnkeywords and the semicolon:
第一种方法是删除返回关键字和分号:
var expression = '2+2+2';
var result = eval('(' + expression + ')')
alert(result);
note the '('and ')'is a must.
注意'('和')'是必须的。
or you can make it a function:
或者你可以把它变成一个函数:
var expression = 'return 2+2+2;'
var result = eval('(function() {' + expression + '}())');
alert(result);
even simpler, do not use eval:
更简单的是,不要使用 eval:
var expression = 'return 2+2+2;';
var result = new Function(expression)();
alert(result);
回答by Matt
If you can guarantee the return
statement will always exist, you might find the following more appropriate:
如果您可以保证该return
语句将始终存在,您可能会发现以下更合适:
var customJSfromServer = "return 2+2+2;"
var asFunc = new Function(customJSfromServer);
alert(asFunc()) ;// should be "6";
Of course, you could also do:
当然,你也可以这样做:
var customJSfromServer = "return 2+2+2;"
var evalValue = (new Function(customJSfromServer)());
alert(evalValue) ;// should be "6";
回答by chim
var customJSfromServer = "2+2+2;"
var evalValue = eval(customJSfromServer);
alert(evalValue) ;// should be "6";
回答by Alex Ciminian
This works:
这有效:
function answer() {
return 42;
}
var a = eval('answer()');
console.log(a);
You need to wrap the return inside a function and it should pass the value on from the eval.
您需要将返回值包装在一个函数中,并且它应该从 eval 传递值。
回答by SergeS
There should not be return statement , as eval will read this as statment and will not return value.
不应该有 return 语句,因为 eval 会将其读为语句并且不会返回值。
var customJSfromServer = "2+2+2;"
var evalValue = eval( customJSfromServer );
alert(evalValue) ;// should be "6";
回答by Matjaz Muhic
Modify server response to get "2+2+2" (remove "return") and try this:
修改服务器响应以获取“2+2+2”(删除“return”)并尝试以下操作:
var myvar = eval(response);
alert(myvar);
回答by leoncc
In 2019 using Template Literals:
2019 年使用模板文字:
var customJSfromServer = "2+2+2;"
var evalValue = eval(`${customJSfromServer}`);
alert(evalValue) ;// should be "6";