Home > Web Front-end > JS Tutorial > How to define dynamic variables in javascript

How to define dynamic variables in javascript

醉折花枝作酒筹
Release: 2023-01-07 11:44:25
Original
5868 people have browsed it

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).

How to define dynamic variables in javascript

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);
Copy after login

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[&#39;hello&#39;] = "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);
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template