Home > Article > Web Front-end > How to Dynamically Access Global Variables by Name in JavaScript?
Question:
Consider the following JavaScript code:
<script> //in script 1 var someVarName_10 = 20; </script>
How can you access the variable someVarName_10 from a different script using its variable name?
<script> const num = 10; alert(all_vars['someVar' + 'Name_' + num]); </script>
Answer:
Yes, it is possible to access local variables by name using the window object:
<script> //in script 2 alert(window["someVarName_10"]); //alerts 20 </script>
Updated Answer (for edited question):
If you access the window object directly, you can concatenate the variable name dynamically using brackets notation:
<script> const num = 10; alert(window['someVar' + 'Name_' + num]); //alerts 20 </script>
The above is the detailed content of How to Dynamically Access Global Variables by Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!