如何使用js eval返回值? [英] How can I use js eval to return a value?

查看:94
本文介绍了如何使用js eval返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要评估从服务器传递的自定义函数作为字符串。这是我得到的复杂json的一部分,但无论如何,我似乎需要一些东西:

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:

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 ?

推荐答案

第一种方法是删除返回关键字和分号:

The first method is to delete return keywords and the semicolon:

var expression = '2+2+2';
var result = eval('(' + expression + ')')
alert(result);

注意'('')'是必须的。

或者你可以使它成为一个函数:

or you can make it a function:

var expression = 'return 2+2+2;'
var result = eval('(function() {' + expression + '}())');
alert(result);

更简单,不要使用eval:

even simpler, do not use eval:

var expression = 'return 2+2+2;';
var result = new Function(expression)();
alert(result);

这篇关于如何使用js eval返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆