Getting access to global variables during runtime can be a common requirement. Typically, global variables can be accessed via the window object. However, this becomes challenging when trying to access local variables across different scripts.
One approach is to use the window object to store and retrieve variables. By referencing the global scope, variables can be accessed dynamically using their names.
// One Script var someVarName_10 = 20; // Another Script window.all_vars = {}; window.all_vars['someVarName_10'] = someVarName_10; const num = 10; alert(window['someVar' + 'Name_' + num]);
This method effectively allows you to retrieve the variable someVarName_10 by dynamically building its name based on the value of num. The resulting alert will display the value of the variable.
The above is the detailed content of How to Access Global Variables Dynamically by Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!