user763349 user763349 - 1 year ago 83
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download