"变量" Javascript中的变量? [英] "Variable" variables in Javascript?

查看:153
本文介绍了"变量" Javascript中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在PHP中有可能拥有变量变量。例如

I know it's possible in PHP to have "variable" variables. For example

$x = "variable";
$$x = "hello, world!";
echo $variable; // displays "hello, world!"

这是否可以在javascript中使用?如何做?

Is this possible in javascript? How would it be done?

推荐答案

没有单一的解决方案(好吧,有 eval ,但不要认真考虑那个)。可以通过窗口动态访问某些全局变量,但这对于函数本地变量不起作用。 成为 window 属性的全局变量是使用 let 和<定义的变量code> const , class es。

There is no single solution for this (well, there is eval, but lets not seriously consider that). It is possible to access some global variables dynamically via window, but that doesn't work for variables local to a function. Global variables that do not become a property of window are variables defined with let and const, and classes.

那里几乎总是比使用变量变量更好的解决方案!相反,你应该看看数据结构并为您的问题选择合适的。

There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.

如果您有一组固定的名称,例如

If you have a fixed set of names, such as

// BAD
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));

将这些名称/值存储为的属性对象并使用括号表示法动态查找它们:

store the those name/values as properties of an object and use bracket notation to look them up dynamically:

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

ES2015 + 中,它更容易做到这对于使用简明属性表示法的现有变量

In ES2015+ it's even easier to do this for existing variables using concise property notation:

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);

如果您有连续编号的变量,例如

If you have "consecutively" numbered variables, such as

// BAD
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

然后你应该使用<强>数组而只是使用索引来访问相应的值:

then you should be using an array instead and simply use the index to access the corresponding value:

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);

这篇关于&QUOT;变量&QUOT; Javascript中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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