Javascript 相当于 PHP 的 $$varName
在 PHP 中,我可以:
$theVariable = "bigToe";
$bigToe = "is broken";
这样:
echo "my ".$theVariable." ".$$theVariable;
将显示
my bigToe is broken
我将如何做与 JavaScript 中类似的事情?
Possible Duplicate:
How to access javascript variable value by creating another variable via concatenation?
In PHP I can have:
$theVariable = "bigToe";
$bigToe = "is broken";
such that:
echo "my ".$theVariable." ".$theVariable;
would display
my bigToe is broken
How would I go about doing something similar to that in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有一篇关于 JavaScript 中动态变量的非常好的文章:
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
There is a pretty good write-up on Dynamic Variables in JavaScript here:
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
我将使用
window
数组而不是eval
:I would use the
window
array instead ofeval
:简单地
说,尽管您必须确保知道您评估的确切值,因为如果您传递不受信任的内容,它可以用于脚本注入
Simply
Although you have to be sure you know the exact value your evaling as it can be used for script injection if you're passing it untrusted content
一种方法是使用 eval 函数
另一种方法是使用 window 对象,该对象保存每个全局变量的键值对。它可以作为数组访问:
两种方法都将答案打印到 Firebug 控制台。
One way is to use the
eval
functionAnother way is to use the
window
object, which holds the key-value pair for each global variable. It can accessed as an array:Both methods print the answer to the Firebug console.