This article describes how JS uses eval() to dynamically create variables. Share it for your reference, as follows:
1. What is the eval() function?
The eval_r() function can calculate a string and execute the JavaScript code in it.
2. How to dynamically define variables?
Since eval() can calculate strings, why not convert the writing method of defining variables into strings and then put them into the eval_r() function for execution, as shown in:
var defineStr = "var number_"+i.toString();eval_r(defineStr);
This defines a variable. You can set debugger to track and debug it to see if the number variable is defined successfully.
If the i value is 1, then the dynamic variable is number_1
It can also be assigned values in this form in the future:
eval_r("number_"+i.toString()+" = 120;");This will assign the value to its variable number_1 to 120.
But this is absolutely not allowed to be written here:
eval_r("number_"+i.toString()) = 120This kind of writing exists in the error of law.
The above writing method is somewhat unworkable in IE. You need to use executeScript (string) to execute. The judgment is as follows:
if(window.executeScript){//IE browser window.executeScript(defineStr);}else{//No IE browser window.eval_r(defineStr);}For more information about JavaScript, please check this site's special topics: "Summary of Ajax Operation Skills in JavaScript", "Summary of JSON Operation Skills in JavaScript", "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.