Convert string to variable name in JavaScript

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

    You can access the window object as an associative array and set it that way

    window["onlyVideo"] = "TEST";
    document.write(onlyVideo);
    
    0 讨论(0)
  • 2020-11-22 03:40

    If it's a global variable then window[variableName] or in your case window["onlyVideo"] should do the trick.

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

    It can be done like this

    (function(X, Y) {
      
      // X is the local name of the 'class'
      // Doo is default value if param X is empty
      var X = (typeof X == 'string') ? X: 'Doo';
      var Y = (typeof Y == 'string') ? Y: 'doo';
      
      // this refers to the local X defined above
      this[X] = function(doo) {
        // object variable
        this.doo = doo || 'doo it';
      }
      // prototypal inheritance for methods
      // defined by another
      this[X].prototype[Y] = function() {
        return this.doo || 'doo';
      };
      
      // make X global
      window[X] = this[X];
    }('Dooa', 'dooa')); // give the names here
    
    // test
    doo = new Dooa('abc');
    doo2 = new Dooa('def');
    console.log(doo.dooa());
    console.log(doo2.dooa());

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

    let me make it more clear

    function changeStringToVariable(variable, value){
    window[variable]=value
    }
    changeStringToVariable("name", "john doe");
    console.log(name);
    //this outputs: john doe
    let file="newFile";
    changeStringToVariable(file, "text file");
    console.log(newFile);
    //this outputs: text file
    
    0 讨论(0)
  • 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()

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