Get variable from a string

前端 未结 5 1463
迷失自我
迷失自我 2020-12-11 08:44

Does anyone know how could I select a variable from a String in JavaScript? Here\'s what I\'m basically trying to achieve:

var myLang = \"ESP\";

var myText_         


        
相关标签:
5条回答
  • 2020-12-11 09:20

    You can use eval for that but this is very bad practice:

    console.log(eval("myText_" + myLang);
    

    I'll suggest to have an object instead:

    var myLang = "ESP";
    var texts = {
        'ESP': "Hola a todos!",
        'ENG': "Hello everyboy!"
    };
    console.log( texts[ myLang ] );
    
    0 讨论(0)
  • 2020-12-11 09:29
    var myLang = "ESP";
    
    var myText = {
        ESP : "Hola a todos!",
        ENG : "Hello everybody!"
    }
    
    console.log(myText[myLang]); // This should trace "Hola a todos!"
    
    0 讨论(0)
  • 2020-12-11 09:32

    It is not a good pratice, but you can try using eval() function.

    var myLang = "ESP";
    
    var myText_ESP = "Hola a todos!";
    var myText_ENG = "Hello everyboy!";
    
    console.log(eval('myText_' + myLang));
    
    0 讨论(0)
  • 2020-12-11 09:39
    var hellos = {
        ESP: 'Hola a todos!',
        ENG: 'Hello everybody!'
    };
    
    var myLang = 'ESP';
    
    console.log(hellos[myLang]);
    

    I don't like putting everything in global scope, and then string accessing window properties; so here is another way to do it.

    0 讨论(0)
  • 2020-12-11 09:41

    If your variable is defined in the global context, you may do this :

    console.log(window['myText_' + myLang]); 
    
    0 讨论(0)
提交回复
热议问题