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

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

DDD
Release: 2024-11-11 10:40:03
Original
758 people have browsed it

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

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!

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