Variables in JavaScript Variables
P粉212971745
2023-08-24 18:55:11
<p>I know it's possible to have "mutable" variables in PHP. For example, </p>
<pre class="brush:php;toolbar:false;">$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
</pre>
<p>Is it possible to reference a variable by name as a string in JavaScript? how should I do it? </p>
If you desperately want to do this, you can try using eval():
Or use window object:
tl;dr: Don't use
eval
!There is no single solution to this. It is possible to dynamically access
some
global variables through the window , but this does not apply to local variables of a function. Global variables that do not becomewindow
attributes are variables defined withlet
andconst
, andclasses.
There is almost always a better solution than using mutable variables! Instead, you should look at data structures and choose the correct data structure for your problem.
If you have a fixed set of names like