Home >Web Front-end >JS Tutorial >How Can I Use Dynamic Variable Names in JavaScript?
Using Dynamic Variable Names in JavaScript
In PHP, it's possible to manipulate variable names dynamically. For instance, given the following PHP code:
$a = 1; $b = 2; $c = 3; $name = 'a'; echo $$name; // prints 1
Is there an equivalent way to achieve this functionality in JavaScript?
JavaScript Solution
While JavaScript does not support dynamic variable names in the same way as PHP, it does provide a mechanism for accessing variables dynamically using the object and property dot or bracket notation.
Like other programming languages, every variable in JavaScript is stored in an object called the Variable Object, which is part of the current scope (either global or local).
If we have the following global variables:
var a = 1; var b = 2; var c = 3;
We can access them dynamically by using the "dot" or "bracket" notation on the window object, which is the global object in browsers:
var name = "a"; var value = window[name]; // returns 1 // or value = window['a']; // returns 1
It's important to note that this approach only works for the global object. Within a function context, variables are stored in the Variable Object of the Activation Object, which is not directly accessible.
For example:
function foobar() { this.a = 1; this.b = 2; var name = "a"; console.log(window['a']); // undefined console.log(this['a']); // 1 } new foobar();
The above is the detailed content of How Can I Use Dynamic Variable Names in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!