Home >Web Front-end >JS Tutorial >How to Dynamically Retrieve Local Variables by Name in JavaScript?
In JavaScript, accessing global variables by name is straightforward using the window object. But what about local variables defined within a specific script? Can they be accessed dynamically by their names?
One method involves taking advantage of the global scope:
//in one script var someVarName_10 = 20; //in another script alert(window["someVarName_10"]); //alert 20
However, this approach may not be ideal as it relies on the variable being added to the global scope.
Another alternative is to utilize the eval() function:
//in one script var num = 10; alert(eval('someVarName_' + num)); //alert 20
This method evaluates the string expression and returns the value of the corresponding variable.
Note: It's important to consider potential security implications when using the eval() function.
The above is the detailed content of How to Dynamically Retrieve Local Variables by Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!