如何使用包含变量名称的字符串来引用变量?

如何使用包含变量名称的字符串来引用变量?

问题描述:

有没有办法用包含其名称的字符串来引用 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));

如果您发现自己需要这样做,更好的方法是使用哈希表.

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