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?
The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.
There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.
The eval() function executes this and creates the variable with the assigned values. The code is given below implements the creation of dynamic variable names using eval(). Window object: JavaScript always has a global object defined.
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));
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);
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With