Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create javascript variables from an array?

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?

like image 644
MerC Avatar asked Aug 04 '12 08:08

MerC


People also ask

Can I create dynamic variable in JavaScript?

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.

How do you dynamically add values to an array of objects in JavaScript?

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.

How do you create a dynamic variable?

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.


3 Answers

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));
like image 188
KooiInc Avatar answered Nov 08 '22 18:11

KooiInc


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);
like image 37
Tom Avatar answered Nov 08 '22 17:11

Tom


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"];
like image 20
Ilya Tsuryev Avatar answered Nov 08 '22 19:11

Ilya Tsuryev