In JavaScript, you can use the function keyword to define dynamic variables. JavaScript functions are defined through the function keyword, followed by the function name and parentheses. Function names can contain letters, numbers, underscores, and dollar signs (the same rules as variable names).
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Dynamicly generate global variables:
//简单的用字符串作为变量名 window['hello'] = "hello, world"; alert(hello); //批量定义 for(var i=0; i<10; i++) { var varname="var"+i; window[varname] = "value"+i; } alert(var0); alert(var9);
Explanation: All global variables exist in window variables. Window is a variable defined by js itself, and its type is object.
Accessing the global variable var0 is equivalent to accessing window.var0, which is also equivalent to window["var0"].
It’s best to use object for local variables:
function test() { var vars = {}; // 简单的字符串作为变量名 vars['hello'] = "hello, world!"; alert(vars.hello); //批量定义 for(var i=0; i<10; i++) { var varname="var"+i; vars[varname] = "value"+i; } alert(vars.var0); alert(vars.var9); }
Same as above, except that you can’t call variables implicitly, but you have to write out object (vars above) explicitly
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to define dynamic variables in javascript. For more information, please follow other related articles on the PHP Chinese website!