user763349 user763349 - 1 month ago 5
Javascript Question

JavaScript: Dynamically Creating Variables for Loops

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.....

Answer

You should use an array:

function createVariables(){
  var accounts = [];

  for (var i = 0; i <= 20; ++i) {
      accounts[i] = "whatever";
  }

  return accounts;
}

You then have access to accounts[0] through accounts[20].

Comments