Variables in JavaScript Variables
P粉212971745
P粉212971745 2023-08-24 18:55:11
0
2
448
<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>
P粉212971745
P粉212971745

reply all(2)
P粉494151941

If you desperately want to do this, you can try using eval():

var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);

Or use window object:

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
P粉893457026

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 become window attributes are variables defined with let and const, and classes.

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

// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!