“变量"JavaScript 中的变量 [英] "Variable" variables in 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: 不要使用eval
!
对此没有单一的解决方案.可以通过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 class
es.
几乎总有比使用可变变量更好的解决方案!相反,您应该查看 数据结构并为您的问题选择正确的结构.
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屋!