Introduction and application examples of JavaScript eval of function

  • 2020-03-30 03:38:18
  • OfStack

The eval(String) function evaluates a String and executes the JavaScript code in it.

The return value

The value obtained by evaluating the string, if any.

instructions

This method accepts only the original string as an argument, and if the string argument is not the original string, the method returns unchanged. So don't pass a String object as an argument to the eval() function.

The ECMAScript implementation allows an EvalError exception to be thrown if you try to override the eval property or assign the eval() method to another property and invoke it through that property.

throw

If there are no valid expressions and statements in the arguments, a SyntaxError exception is thrown.

If eval() is called illegally, an EvalError exception is thrown.

If the Javascript code passed to eval() generates an exception, eval() passes the exception to the caller.

Hints and comments

Tip: while eval() is very powerful, it's not used very often in practice.

Example:


<html>
<body>

<script type="text/javascript">

eval("x=10;y=20;document.write(x*y)")
document.write("<br />")

document.write(eval("2+2"))
document.write("<br />")

var x=10
document.write(eval(x+17))
document.write("<br />")

eval("alert('Hello world')")

</script>

</body>
</html>

Output:

200

4

24


Related articles: