Home  >  Article  >  Web Front-end  >  How to Dynamically Access Global Variables by Name in JavaScript?

How to Dynamically Access Global Variables by Name in JavaScript?

DDD
DDDOriginal
2024-11-12 09:11:01434browse

How to Dynamically Access Global Variables by Name in JavaScript?

Dynamically Accessing 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn