Home  >  Article  >  Web Front-end  >  How Can I Dynamically Access Global Variables by Name in JavaScript?

How Can I Dynamically Access Global Variables by Name in JavaScript?

DDD
DDDOriginal
2024-11-11 10:40:03656browse

How Can I Dynamically Access Global Variables by Name in JavaScript?

Dynamically Access Global Variables by Name in JavaScript

In JavaScript, accessing global variables by name is straightforward using the window object. However, this method only works for true global variables. Local variables defined within a script are not accessible outside its scope.

For such variables, a workaround is to expose them as properties of the window object. This allows you to access them dynamically by concatenating a name string:

// In one script
var someVarName_10 = 20;
window["someVarName_10"] = someVarName_10;

// In another script
const num = 10;
alert(window["someVar" + "Name_" + num]); // 20

Please note that accessing local variables in this manner introduces additional coupling between your scripts and can make your code harder to debug. It should only be used when necessary.

The above is the detailed content of How Can I Dynamically Access Global Variables by Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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