Javascript 中的“变量”变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5187530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Variable" variables in Javascript?
提问by ShoeLace1291
I know it's possible in PHP to have "variable" variables. For example
我知道在 PHP 中可能有“可变”变量。例如
$x = "variable";
$$x = "hello, world!";
echo $variable; // displays "hello, world!"
Is it possible to refer to a variable by its name as a string in javascript? How would it be done?
是否可以在 javascript 中通过名称将变量引用为字符串?怎么做?
回答by Felix Kling
There is no single solution for this (well, there is eval
, but lets not seriously consider that). It is possible to access someglobal variables dynamically via window
, but that doesn't work for variables local to a function. Global variables that do notbecome a property of window
are variables defined with let
and const
, and class
es.
对此没有单一的解决方案(嗯,有eval
,但我们不要认真考虑)。可以通过 动态访问某些全局变量window
,但这不适用于函数的局部变量。不成为 属性的全局变量是window
用let
andconst
和class
es定义的变量。
There is almost always a better solution than using variable variables!Instead you should be looking at data structuresand 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 objectand use bracket notationto look them up dynamically:
将这些名称/值存储为对象的属性并使用括号表示法动态查找它们:
// GOOD
var obj = {
foo: 42,
bar: 21,
};
var key = 'foo';
console.log(obj[key]);
In ES2015+it's even easier to do this for existing variables using concise property notation:
在ES2015+ 中,使用简洁的属性符号对现有变量执行此操作更容易:
// 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 arrayinstead and simply use the index to access the corresponding value:
那么您应该改用数组并简单地使用索引来访问相应的值:
// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);
回答by Masterbuddha
If you are desperate to do this you can either try using eval():
如果您不顾一切地这样做,您可以尝试使用 eval():
var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);
Or using the window object:
或者使用 window 对象:
var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript
回答by Awesomeness01
To reference a variable in javascript with only a string, you can use
要仅使用字符串引用 javascript 中的变量,您可以使用
window['your_variable_name']
You can set and reference variables, and objects in variables too.
您也可以设置和引用变量以及变量中的对象。
回答by Nadav
Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a gloabls array for you. For example, instead of declaring the variable hello
in the global scope like this:
与 PHP 不同,JavaScript 不提供对 globals 数组(包含对当前声明的所有变量名的引用)的访问。因此,JavaScript 不提供对变量变量的原生支持。但是,只要将所有变量定义为数组或对象的一部分,就可以模拟此功能。这将反过来为您创建一个 globals 数组。例如,不要hello
像这样在全局范围内声明变量:
var hello = 'hello world';
let's encapsulate it inside an object. We'll call that object vv (variable variables):
让我们把它封装在一个对象中。我们将该对象称为 vv(变量变量):
var vv = {
'hello': 'hello world',
//Other variable variables come here.
},
referToHello = 'hello';
Now we can refer to the variable by it's index, and since array indexes can be provided using a variable we are de facto making use of a variable variable:
现在我们可以通过它的索引来引用变量,并且由于可以使用变量提供数组索引,我们实际上是在使用变量变量:
console.log(vv[referToHello]); //Output: hello world
The Answer To Your Question
您问题的答案
Let's apply this to the code you supplied in the original question:
让我们将此应用于您在原始问题中提供的代码:
var vv = {
'x': 'variable',
'variable': 'hello world!'
};
console.log(vv[vv['x']]); //Displays "hello, world!"
A Practical Use
实际用途
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
虽然前面的代码可能看起来非常繁琐和不切实际,但在 JavaScript 中使用这种类型的封装变量变量有实际用途。在下面的示例中,我们使用相同的概念来获取未定义数量的 HTML 元素的 ID。
var elementIds = [],
elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
elements.forEach( (element) => {
elementIds[element] = document.getElementById(element);
});
This example declares variable variables (keys in elementIds
) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds
array) is not only neat, but also more responsible.
本示例elementIds
根据每个元素的 ID声明变量变量(keys in ),并将该元素的节点分配为每个变量的值。因为在 JavaScript 中使用全局变量通常是不鼓励的,所以给你的变量变量一个唯一的范围(在这种情况下,在elementIds
数组中声明它们)不仅整洁,而且更负责任。
回答by Konrad Borowski
Of course you can, but don't. The variables have to be global.
当然可以,但不要。变量必须是全局的。
var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])
回答by lkdhruw
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
回答by Abraham Murciano Benzadon
You can use the JavaScript eval(str)
function.
您可以使用 JavaScripteval(str)
函数。
What this function does is convert the string provided into JS code, then executes it.
这个函数的作用是将提供的字符串转换成JS代码,然后执行。
For example:
例如:
eval("console.log('hello world')"); // Logs hello world
So to use it as a variable variable, you can do the following:
因此要将其用作可变变量,您可以执行以下操作:
var a = "hello";
var hello = "world";
console.log(a + " " + eval(a)); // Logs hello world
This will produce the exact same output as:
这将产生与以下完全相同的输出:
console.log(a + " " + hello); // Logs hello world
(Example is taken from the PHP manual on variable variables.)
(示例取自关于变量变量的 PHP 手册。)