JavaScript: Dynamically Creating Variables for Loops

Viewed 123584

How can I use a for loop to dynamically create variables, and be returned.

function createVariables()
{
for ( i=0; i<=20; i++ )
    {
        var account = i;
        return var account + i;
    }
 }

The goal is to have the result below:

var account1;
var account2;
var account3; and etc.....
10 Answers

I find this a simplest solution

for (var i = 0; i < 10; i++) {
   this["RONAK"+i] = "MY VAL";
}

Output

RONAK0 = "MY VAL"
RONAK1 = "MY VAL"
RONAK2 = "MY VAL"
...
RONAK9 = "MY VAL"

You can use the eval() method to declare dynamic variables as it executes JavaScript statements passed to it.

function createVariables()
{
    for ( i=0; i<=20; i++ )
    {
        var str ="account"+ i+" = undefined";
        //Declaring and Setting dynamic variable to undefined using eval
        eval(str);
    }
}
createVariables();
function createVariables() {
    var accounts = [];
    for (var i = 0; i <= 20; ++i) {
        accounts[i] = "merhaba" + i;
    }
    return accounts;
}

The following code will actually create variables, instead of creating this sort of hash table proposed by @Domenic

    function createVariables(){
        var varName = "accounts";

        for (var i = 0; i <= 20; ++i) {
            eval('var ' + varName + i + ' = ' + '"whatever"' + ';');
        }

        return accounts;
    }

I was pretty proud of the way I made iterating variables with my code, was going to share it but I think I'll just sort of show you modified version of it.

function variableBuilder() {
   let i = 0;
   while (i <= 20) {
      let accountVariable = "account".concat(i);
      `// variable can even be reassigned here`
      console.log(accountVariable);
      i++;
   }
}

you can use the variable as an iterating variable identifier, in the spot that I suggested; I used this method to build DOM nodes, to create a dynamically built HTML table.

we can use map for it.

var map = {};
for (var i = 0; i < 10; ++i) {
  map["nutrient" + i] = "some stuff" + i;
}
console.log(map)

result:

{
  nutrient0: 'some stuff0',
  nutrient1: 'some stuff1',
  nutrient2: 'some stuff2',
  nutrient3: 'some stuff3',
  nutrient4: 'some stuff4',
  nutrient5: 'some stuff5',
  nutrient6: 'some stuff6',
  nutrient7: 'some stuff7',
  nutrient8: 'some stuff8',
  nutrient9: 'some stuff9'
}
Related