Home  >  Q&A  >  body text

Variables in JavaScript Variables

<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粉212971745P粉212971745443 days ago526

reply all(2)I'll reply

  • P粉494151941

    P粉4941519412023-08-25 16:40:34

    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]);

    reply
    0
  • P粉893457026

    P粉8934570262023-08-25 11:49:08

    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));

    reply
    0
  • Cancelreply