在 JavaScript 中使用动态变量名 [英] Use dynamic variable names in JavaScript

查看:23
本文介绍了在 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 = 'the name of the variable'; 我可以获得名称为 name 的变量的引用吗?

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 都是关于 ObjectsContexts(它们也是某种对象),每个变量都存储在一个名为 Variable-(或者在函数的情况下,激活对象)中.

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;

全局范围(=无函数上下文)中,您将这些变量隐式写入全局对象(=浏览器中的window).

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

这仅适用于此特定实例中的全局对象,因为 全局对象变量对象window 对象本身.在函数的上下文中,您不能直接访问激活对象.例如:

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).这个例子会分别提醒 undefined1 .如果我们要替换 this.a = 1;this.b = 2 与:

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;

两个警报输出都将是未定义的.在这种情况下,变量 ab 将存储在来自 foobar 的激活对象中,我们无法访问(当然我们可以访问那些直接通过调用ab).

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屋!

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