javascript 如何从数组动态创建javascript变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11807231/
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
How to dynamically create javascript variables from an array?
提问by MerC
Lets say I have an array of names for a variable:
假设我有一个变量名称数组:
var varNames = new Array("name1","name2","name3");
How do I create var name1
, var name2
and var name3
by just looping through the varNames
array?
我如何创建var name1
,var name2
并var name3
通过循环遍历varNames
数组?
回答by KooiInc
This will create global variables (in the global namespace, i.e. window
).
这将创建全局变量(在全局命名空间中,即window
)。
var varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
window[varNames[i]] = 0;
}
name1; //=> 0
Since using global variables is considered bad practice, you could create variables within a custum object:
由于使用全局变量被认为是不好的做法,您可以在 custum 对象中创建变量:
var myVariables = {}
,varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
}
myVariables.name1; //=> 0
Edit 2017
编辑 2017
Using es≥6:
使用es≥6:
const [v1, v2, v3] = ["name1","name2","name3"];
console.log(v1); // => name1
回答by Tom
You can do it as follows. I added the alerts to prove you can set a value to those variables.
您可以按如下方式进行。我添加了警报以证明您可以为这些变量设置一个值。
var varNames = new Array("name1","name2","name3");
for(var i = 0; i < varNames.length; i++) {
window[varNames[i]] = i;
}
alert("name1: " + name1);
alert("name2: " + name2);
alert("name3: " + name3);
回答by Ilya Tsuryev
The direct answer to your question would be - you can do it using eval
:
您问题的直接答案是 - 您可以使用eval
:
var varNames = new Array("name1","name2","name3");
for (var i=0; i<varNames.length; i++) {
var varName = varNames[i];
eval("var "+varName); // would be "var name1"
}
Please note though this is considered bad practice and usually there is no justification for using eval for such case. Also note that it's more common to create array using following style:
请注意,虽然这被认为是不好的做法,但通常没有理由在这种情况下使用 eval。另请注意,使用以下样式创建数组更为常见:
var varNames = ["name1", "name2", "name3"];