在JavaScript中使用动态变量名称 [英] Use dynamic variable names in JavaScript
问题描述
在PHP中你可以做出如下惊人/可怕的事情:
In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
有没有办法用Javascript做这样的事情?
Is there any way of doing something like this with Javascript?
例如如果我有 var name ='变量的名称';
我可以获得名称 name $ c $的变量的引用c>?
E.g. if I have a var name = 'the name of the variable';
can I get a reference to the variable with name name
?
推荐答案
由于ECMA- / Javascript完全是关于对象
和上下文
(其中也是某些Object),每个变量都存储在一个名为变量 - 的情况下(或者在函数的情况下, 激活对象)。
Since ECMA-/Javascript is all about Objects
and Contexts
(which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
因此,如果您创建如下变量:
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
在全局范围(= NO函数上下文)中,您隐式写那些变量进入全局对象(= 窗口
在浏览器中)。
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window
in a browser).
那些可以使用点或括号表示法访问:
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
或
var name = window['a'];
这仅适用于此特定实例中的全局对象,因为变量对象 全局对象是窗口
对象本身。在函数的上下文中,您无法直接访问激活对象。例如:
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window
object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar() {
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
alert(name);
name = this['a']; // === 1
alert(name);
}
new foobar();
new
创建一个新的自我实例 - 定义的对象(上下文)。如果没有 new
,该函数的范围也将是 global
(= window)。此示例将分别提醒 undefined
和 1
。如果我们要替换 this.a = 1; this.b = 2
with:
new
creates a new instance of a self-defined object (context). Without new
the scope of the function would be also global
(=window). This example would alert undefined
and 1
respectively. If we would replace this.a = 1; this.b = 2
with:
var a = 1,
b = 2;
两个警报输出都是未定义的。在这种情况下,变量 a
和 b
将从 foobar存储在激活对象中
,我们无法访问(当然我们可以通过调用 a
和 b
)。
Both alert outputs would be undefined. In that scenario, the variables a
and b
would get stored in the Activation Object from foobar
, which we cannot access (of course we could access those directly by calling a
and b
).
这篇关于在JavaScript中使用动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!