Home > Web Front-end > JS Tutorial > body text

How to Dynamically Access Global Variables by Name in JavaScript?

DDD
Release: 2024-11-12 09:11:01
Original
421 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template