Reputation: 323
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?
Upvotes: 9
Views: 24037
Reputation: 123016
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
[ES20xx]
const myVariables = ['name1', 'name2', 'name3']
.reduce( (a, v, i) => ({...a, [v]: i + 1 }), {});
console.log(JSON.stringify(myVariables, null, 2));
// to 'global' variables
Object.entries(myVariables).forEach( ([key, value]) =>
window[key] = value );
console.log(`name1: ${name1}, name2: ${name2}`);
Upvotes: 14
Reputation: 2846
The direct answer to your question would be - you can do it using 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:
var varNames = ["name1", "name2", "name3"];
Upvotes: 2
Reputation: 4180
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);
Upvotes: 2