Convert string to variable name in JavaScript

后端 未结 11 1553
无人及你
无人及你 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.

    0 讨论(0)
  • 2020-11-22 03:29

    The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.

    (function(){
        var findMe = 'no way';
    })();
    
    0 讨论(0)
  • 2020-11-22 03:31

    You can do like this

    var name = "foo";
    var value = "Hello foos";
    eval("var "+name+" = '"+value+"';");
    alert(foo);

    0 讨论(0)
  • 2020-11-22 03:37
    var myString = "echoHello";
    
    window[myString] = function() {
        alert("Hello!");
    }
    
    echoHello();
    

    Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/

    0 讨论(0)
  • 2020-11-22 03:37

    The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.

    // For each element with an id (example: 'MyDIV') in the body, create a variable
    // for easy reference. An example is below.
    var D=document;
    var id={}; // All ID elements
    var els=document.body.getElementsByTagName('*');
    for (var i = 0; i < els.length; i++)
        {
        thisid = els[i].id;
        if (!thisid)
            continue;
        val=D.getElementById(thisid);
        id[thisid]=val;
        }
    
    // Usage:
    id.MyDIV.innerHTML="hello";
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题