This is the 9th day of my participation in the August More Text Challenge.
describe
The eval() function evaluates a string and executes the JavaScript code inside it.
Eval () is a function property of a global object.
The argument to eval() is a string. If a string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript statements, eval() executes those statements. You don’t need eval() to execute an arithmetic expression: JavaScript evaluates arithmetic expressions automatically.
If you construct an arithmetic expression as a string, you can evaluate it later with eval(). For example, if you have a variable x, you can delay the evaluation of expressions involving x by assigning the expression’s string value (such as 3 * x + 2) to a variable, and then calling eval() elsewhere after your code.
If the argument to eval() is not a string, eval() returns the argument as it is.
1. Eval (
Parse string arguments into JS code and run it, and return the result of execution; Such as:
eval("2 + 3");// return 5 ; Performs the addition operation and returns the value of the operation.
eval("varage=10");// Declare an age variable
Copy the code
2. Scope for eval
In all its scope the content is valid for example
1:function a(){
eval("var x=1"); Var x=1;
console.log(x); / / output 1
}
a();
console.log(x);// Error x is not definedThe sample2:functiona(){
window.eval("var x=1"); // equivalent to window.x=1; Defines global variables
console.log(x); / / output 1
}
a();
console.log(x);/ / output 1
Copy the code
3. Precautions
Eval should be avoided as it is unsafe and very performance intensive (execute twice, parse once into JS statement, execute once)
It is not supported in IE8 and later versions
4. Other functions
We can use eval to convert JSON strings into JSON objects, for example:
var json="{name:'Mr.gao',age:30}";
var jsonObj=eval("("+json+")");
console.log(jsonObj); / / o {name: 'Mr. Gao', age: 30}
Copy the code