Variables in JavaScript Variables
P粉212971745
P粉212971745 2023-08-24 18:55:11
0
2
428

I know it's possible to have "mutable" variables in PHP. For example,

$x = "variable"; $$x = "Hello, World!"; echo $variable; // Displays "Hello, World!" 

Is it possible to reference a variable by name as a string in JavaScript? how should I do it?

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 useeval!

    There is no single solution to this. It is possible to dynamically accesssomeglobal variables through thewindow, but this does not apply to local variables of a function.Global variables that do notbecomewindowattributes are variables defined withletandconst, andclasses.

    There is almost always a better solution than using mutable variables!Instead, you should look atdata structuresand 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!