Home  >  Article  >  Web Front-end  >  JavaScript eval() function introduction and application examples_javascript skills

JavaScript eval() function introduction and application examples_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:40:521354browse

The

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

Return value

The value obtained by evaluating string (if any).

Description

This method only accepts raw strings as parameters. If the string parameter is not a raw string, then the method will return unchanged. Therefore please do not pass String objects as arguments to the eval() function.

ECMAScript implementations allow an EvalError exception to be thrown if an attempt is made to override the eval property or assign the eval() method to another property and call it through that property.

Throws

If there are no legal expressions and statements in the parameters, a SyntaxError exception will be thrown.

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

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

Tips and Notes

Tip: Although eval() is very powerful, it is rarely used in actual use.

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn