Get variable from a string

廉价感情. 提交于 2019-11-28 12:43:15
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.

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

console.log(window['myText_' + myLang]); 
var myLang = "ESP";

var myText = {
    ESP : "Hola a todos!",
    ENG : "Hello everybody!"
}

console.log(myText[myLang]); // This should trace "Hola a todos!"

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 ] );

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));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!