Javascript 相当于 PHP 的 $$varName

发布于 2024-08-09 18:51:50 字数 508 浏览 14 评论 0原文

可能的重复:
如何通过创建来访问 javascript 变量值通过串联另一个变量?

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雪花飘飘的天空 2024-08-16 18:51:50

这里有一篇关于 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

心的位置 2024-08-16 18:51:50

我将使用 window 数组而不是 eval

var bigToe = "big toe";
window[bigToe] = ' is broken';
alert("my " + bigToe + window[bigToe]);

I would use the window array instead of eval:

var bigToe = "big toe";
window[bigToe] = ' is broken';
alert("my " + bigToe + window[bigToe]);
晨敛清荷 2024-08-16 18:51:50

简单地

eval("variableName")

说,尽管您必须确保知道您评估的确切值,因为如果您传递不受信任的内容,它可以用于脚本注入

Simply

eval("variableName")

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

江湖正好 2024-08-16 18:51:50

一种方法是使用 eval 函数

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+eval(theVariable));

另一种方法是使用 window 对象,该对象保存每个全局变量的键值对。它可以作为数组访问:

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+window[theVariable]);

两种方法都将答案打印到 Firebug 控制台。

One way is to use the eval function

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+eval(theVariable));

Another way is to use the window object, which holds the key-value pair for each global variable. It can accessed as an array:

var theVariable = "bigToe";
var bigToe = "is broken";
console.log('my '+theVariable+' '+window[theVariable]);

Both methods print the answer to the Firebug console.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文