Javascript,使用包含其名称的字符串引用变量? [英] Javascript, refer to a variable using a string containing its name?
本文介绍了Javascript,使用包含其名称的字符串引用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法用包含其名称的字符串引用Javascript变量?
Is there a way to refer to a Javascript variable with a string that contains its name?
示例:
var myText = 'hello world!';
var someString = 'myText';
//how to output myText value using someString?
推荐答案
您可以使用 eval
要做到这一点,尽管我会不惜一切代价避免这种事情。
You can use an eval
to do it, though I try to avoid that sort of thing at all costs.
alert(eval(someString));
更好的方法是,如果你发现自己需要这样做,就是使用哈希表。 / p>
A better way, if you find yourself needing to do this, is to use a hash table.
var stuff = { myText: 'hello world!' };
var someString = 'myText';
alert( stuff[someString] );
这篇关于Javascript,使用包含其名称的字符串引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文