Convert string to variable name in JavaScript

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

    If you're trying to access the property of an object, you have to start with the scope of window and go through each property of the object until you get to the one you want. Assuming that a.b.c has been defined somewhere else in the script, you can use the following:

    var values = window;
    var str = 'a.b.c'.values.split('.');
    
    for(var i=0; i < str.length; i++)
        values = values[str[i]];
    

    This will work for getting the property of any object, no matter how deep it is.

提交回复
热议问题