JS uses eval () to dynamically create variables, jseval
This article describes how JS uses eval () to dynamically create variables. We will share this with you for your reference. The details are as follows:
1. What is the eval () function?
The eval_r () function computes a string and executes the JavaScript code.
2. How to dynamically define variables?
Since eval () can calculate a string, why not convert the syntax of the defined variable to a string and then put it into the eval_r () function for execution, as shown in:
Var defineStr = "var number _" + I. toString (); eval_r (defineStr );
In this way, a variable is defined. You can set the debugger to trace and debug the variable to see if the number variable is successfully defined.
If the I value is 1, the dynamic variable is number_1.
In the future, you can assign values to them in this form:
Eval_r ("number _" + I. toString () + "= 120 ;");
In this way, the variable number_1 is assigned 120.
However, it is absolutely impossible to write as follows:
Eval_r ("number _" + I. toString () = 120
This write method is incorrect.
The preceding method does not work in IE. You need to use executeScript (string) to execute it. The judgment is as follows:
If(window.exe cuteScript) {// ieviewer window.exe cuteScript (defineStr);} else {// non-ie browsers such as Chrome and Firefox window. eval_r (defineStr );}