How to declare a dynamic local variable in Javascript

前端 未结 7 2177
我在风中等你
我在风中等你 2021-02-04 08:37

I want to create a local variable dynamically. JavaScript: Dynamically Creating Variables for Loops is not exactly what I am looking for. I dont want an array. I want to access

7条回答
  •  走了就别回头了
    2021-02-04 09:28

    This answer is more or less the same as several answers above but here with a simplified sample, with and without using eval. First using eval (not recommended):

    var varname = 'foo';  // pretend a user input that
    var value = 42;
    eval('var ' + varname + '=' + value);
    

    And alternatively, without using eval:

    var varname = prompt('Variable name:');
    var value = 42;
    this[varname] = value;
    

    I hope this helps.

    Source: https://www.rosettacode.org/wiki/Dynamic_variable_names#JavaScript

提交回复
热议问题