eval always returns error when executing a functio

2019-07-04 02:19发布

问题:

This block of code always returns errors:

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

A statement like this works perfectly fine:

eval('alert(1)');

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

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

回答1:

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;} })()');

or

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



回答2:

You can only return from within a function. Like so:

function foo() {
    if (x) alert("woo");
    else return 0;
    doMoreStuff();
 }

You're not in a function, so there's nothing to return from. Also, why are you using eval at all?



回答3:

In the first case, you are attempting to execute an expression with a return. In the second case, you are calling a function that returns a value. To do what you want, you can declare and invoke an anonymous function within the expression as follows...

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

Of course, if the question is just how to construct an evaluateable expression that includes a condition, you can use the "ternary" operator...

eval('var_a ? nil : 0');