从字符串获取变量 [英] Get variable from a string
本文介绍了从字符串获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道如何在JavaScript中从字符串中选择一个变量吗?这是我基本上想要实现的目标:
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_ESP = "Hola a todos!";
var myText_ENG = "Hello everybody!";
console.log(myText_ + myLang); // This should trace "Hola a todos!"
谢谢!
推荐答案
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.
这篇关于从字符串获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文