当执行具有return语句的函数时,eval总是返回错误 [英] eval always returns error when executing a function having a return statement

查看:79
本文介绍了当执行具有return语句的函数时,eval总是返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码块始终返回错误:

This block of code always returns errors:

eval('if(!var_a){return 0;}');

这样的语句可以很好地工作:

A statement like this works perfectly fine:

eval('alert(1)');

诸如eval('return 0')之类的JavaScript语句在其意图是使脚本停止进一步执行时始终会给出错误.

A JavaScript statement such as eval('return 0') always gives an error when its intention is to make the script stop further execution.

eval在某些代码块中运行并且其中包含return语句时,只会给出不必要的错误.

eval simply gives unwanted errors when it is run in some block of code and a return statement is in it.

推荐答案

这是因为您在函数上下文之外使用return.将您的代码包装在一个函数中,然后返回即可正常工作.有几种方法可以做到这一点. 我建议您不要使用其中任何一个.而是找到一种避免评估的方法.无论如何,这里有一些解决方案:

This is because you are using return outside of the context of a function. Wrap your code in a function and return works fine. There are a few ways to do that. I suggest that you do not use any of them. Instead find a way to avoid eval. Regardless, here are some solutions:

eval('(function() { if(!var_a){return 0;} })()');

new Function('if(!var_a){return 0;}')()

这篇关于当执行具有return语句的函数时,eval总是返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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