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

How to Access Global Variables Dynamically by Name in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 06:42:03588browse

How to Access Global Variables Dynamically by Name in JavaScript?

Accessing Global Variables Dynamically by Name in JavaScript

Getting access to global variables during runtime can be a common requirement. Typically, global variables can be accessed via the window object. However, this becomes challenging when trying to access local variables across different scripts.

One approach is to use the window object to store and retrieve variables. By referencing the global scope, variables can be accessed dynamically using their names.

// One Script
var someVarName_10 = 20;

// Another Script
window.all_vars = {};
window.all_vars['someVarName_10'] = someVarName_10;
const num = 10;
alert(window['someVar' + 'Name_' + num]);

This method effectively allows you to retrieve the variable someVarName_10 by dynamically building its name based on the value of num. The resulting alert will display the value of the variable.

The above is the detailed content of How to Access Global Variables Dynamically 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