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

How to Dynamically Retrieve Local Variables by Name in JavaScript?

Linda Hamilton
Release: 2024-11-11 03:33:02
Original
599 people have browsed it

How to Dynamically Retrieve Local Variables by Name in JavaScript?

Dynamic Retrieval of Local Variables by Name in JavaScript

In JavaScript, accessing global variables by name is straightforward using the window object. But what about local variables defined within a specific script? Can they be accessed dynamically by their names?

One method involves taking advantage of the global scope:

//in one script
var someVarName_10 = 20;

//in another script
alert(window["someVarName_10"]); //alert 20
Copy after login

However, this approach may not be ideal as it relies on the variable being added to the global scope.

Another alternative is to utilize the eval() function:

//in one script
var num = 10;
alert(eval('someVarName_' + num)); //alert 20
Copy after login

This method evaluates the string expression and returns the value of the corresponding variable.

Note: It's important to consider potential security implications when using the eval() function.

The above is the detailed content of How to Dynamically Retrieve Local 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template