"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Dynamically Access Global Variables by Name in JavaScript?

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

Published on 2024-11-12
Browse:572

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3