Dynamically Retrieving Global Variables by Name in JavaScript
The need to access global variables dynamically by their name strings can arise in various scenarios. In JavaScript, global variables are declared outside of any function or block, making them accessible throughout the script.
Accessing Global Variables with Window Object
Traditionally, global variables can be accessed using the window object. For instance, if you have a global variable named someVarName_10 with a value of 20, you can retrieve it using:
window["someVarName_10"] //returns 20
Accessing Local Variables Dynamically
However, the question focuses on accessing local variables dynamically by name. In JavaScript, local variables declared within functions or blocks are not accessible outside their scope.
Dynamic Access Only Possible with Global Variables
The solution provided in the answer demonstrates that accessing variables dynamically by name is only possible with global variables. It shows how to use the window object to access a global variable named someVarName_10 and even construct its name dynamically using string concatenation, as in the second code example:
alert(window['someVar' + 'Name_' + num]); //alert 20
Update (Edited Question)
The updated question clarifies the intention of accessing local variables. However, as explained earlier, local variables are not accessible outside their scope and cannot be retrieved dynamically by name.
The above is the detailed content of Can you dynamically access local variables by name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!