Convert string to variable name in JavaScript

后端 未结 11 1694
无人及你
无人及你 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:39

    As far as eval vs. global variable solutions...

    I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

    var tempNamespace = {};
    var myString = "myVarProperty";
    
    tempNamespace[myString] = 5;
    

    Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

提交回复
热议问题