如何使用包含变量名称的字符串来引用变量? [英] How can I refer to a variable using a string containing its name?

查看:21
本文介绍了如何使用包含变量名称的字符串来引用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何使用包含变量名称的字符串来引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆