Convert string to variable name in JavaScript

后端 未结 11 1557
无人及你
无人及你 2020-11-22 02:59

I’ve looked for solutions, but couldn’t find any that work.

I have a variable called onlyVideo.

\"onlyVideo\" the string gets passe

11条回答
  •  盖世英雄少女心
    2020-11-22 03:46

    Javascript has an eval() function for such occasions:

    function (varString) {
      var myVar = eval(varString);
      // .....
    }
    

    Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need

    function SetTo5(varString) {
      var newValue = 5;
      eval(varString + " = " + newValue);
    }
    

    or if using a string:

    function SetToString(varString) {
      var newValue = "string";
      eval(varString + " = " + "'" + newValue + "'");
    }
    

    But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()

提交回复
热议问题