1. Eval is the basic usage rule
•1 The eval() function can calculate a string and execute the JavaScript code in it.
•2 eval(string)
•3 string is required. The string to be calculated contains the JavaScript expression to be calculated or the statement to be executed.
•4 eval() has only one parameter.
•5 Eval is not safe to use, forget to use it carefully
2. Eval's wrong usage method
•1 If the passed parameter is not a string, it returns this function directly.
•2 If the parameter is a string, it will compile the string as JavaScript code, if the compiler fails to throw a syntax error exception.
•3 If the compilation is successful, start executing this code and return the value of the last expression or statement in the string.
•4 If the last expression or statement has no value, undefined is finally returned.
III. Use examples
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>eval</title> </head> <body> <script type="text/javascript"> //Correct input var x = 10; document.write(eval(10*x + 10)) //Expression output 110 document.write("<br />"); document.write(eval("10 == x")); //Expression output true document.write("<br />"); eval(document.write(2+5*x)); //Execution statement output 52 //Abnormal input try{ var y = 8; //Expression document.write(eval("9+6*x"+"100")); //If there are no legal expressions and statements in the parameter, a SyntaxError exception is thrown. document.write("<br />"); eval('++++2'); //Compilation failed ReferenceError exception eval(document.write(2+2)); //Compilation successfully document.write(eval()); //Return undefined var my = eval(); //If you try to overwrite the eval property or assign the eval() method to another property, document.write(my(1+2)); //And call it through this property, the ECMAScript implementation allows an EvalError exception to be thrown. } catch(exception) { alert(exception); } </script> </body> </html>I have checked a lot of information myself, but it is still very vague. I hope that the master who knows can give me some advice!
The above insights on js eval() function are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.