“变量"JavaScript中的变量 [英] "Variable" variables in JavaScript

查看:46
本文介绍了“变量"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 it possible to refer to a variable by its name as a string in JavaScript? How would it be done?

推荐答案

tl; dr:对此没有单一的解决方案.可以通过 window 动态访问一些全局变量,但这不适用于函数本地的变量.成为 window 的属性的全局变量是使用 let const 定义的变量.类 es.

There is no single solution for this. 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 - DON'T DO THIS!!!
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 - DON'T DO THIS!!!
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]);

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

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