本文介绍了如何从数组中动态创建javascript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说一个变量名称的数组: var varNames = new Array(name1, NAME2\" , NAME3);
如何创建 var name1
, var name2
和 var name3
只需循环执行 varNames
array ?
解决方案
这将创建全局变量(在全局命名空间中,即窗口
)。
var varNames = [name1,name2,name3]; (var i = 0; i< varNames.length; i + = 1)
{
window [varNames [i]] = 0;
}
name1; // =>由于使用全局变量被认为是不好的做法,所以可以在custum对象内创建变量:
var myVariables = {}
,varNames = [name1,name2,name3]; (var i = 0; i< varNames.length; i + = 1)
{
myVariables [varNames [i]] = 0;
}
myVariables.name1; // => 0
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?
解决方案
This will create global variables (in the global namespace, i.e. 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:
var myVariables = {}
,varNames = ["name1","name2","name3"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
}
myVariables.name1; //=> 0
这篇关于如何从数组中动态创建javascript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!