Home  >  Article  >  Web Front-end  >  How to use JavaScript eval() function correctly

How to use JavaScript eval() function correctly

jacklove
jackloveOriginal
2018-05-04 15:48:221470browse

The JavaScript eval() function can be used to calculate strings. This article introduces its use in detail.

Definition and usage

eval() function can calculate a string and execute the JavaScript code in it.

Syntax

eval(string)


Parameters: string

Description: Required. A string to evaluate that contains a JavaScript expression to evaluate or a statement to execute.

Return value

The value obtained by calculating string (if any).

Description

This method only accepts original strings as parameters. If the string parameter is not an original string, then the method will return without any changes. Therefore please do not pass String objects as arguments to the eval() function.

The ECMAScript implementation is allowed to throw an EvalError exception if you try 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 is 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

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

Example

Example 1

In this example, we will apply eval() on several strings and see the returned results:

<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)")
document.write(eval("2+2"))
var x=10
document.write(eval(x+17))
</script>

Output:

200
4
27

Example 2

Look at the results returned by eval() in other cases :

eval("2+3")// 返回 5
var myeval = eval;// 可能会抛出 EvalError 异常
myeval("2+3");// 可能会抛出 EvalError 异常

You can use the following code to check whether the parameters of eval() are legal:

try  {     alert("Result:" + eval(prompt("Enter an expression:","")));     }catch(exception) {     alert(exception);     }

This article introduces the use of eval() in detail, more eval () For related knowledge, please pay attention to the php Chinese website.

Related recommendations:

javascript eval() usage_javascript skills

javascript eval() application examples select_javascript skills

JavaScript eval() function introduction and application examples_javascript skills

The above is the detailed content of How to use JavaScript eval() function correctly. For more information, please follow other related articles on the PHP Chinese website!

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