Home > Article > Web Front-end > How Can I 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!