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

How to Access Global Variables Dynamically by Name in JavaScript?

Patricia Arquette
Release: 2024-11-17 06:42:03
Original
508 people have browsed it

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]);
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template