JavaScript: Dynamically Creating Variables for Loops

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


The only way I know how to do this would be to use the JavaScript eval function.

Something like eval("account" + 1 + "='some value'");

http://www.w3schools.com/jsref/jsref_eval.asp

However, I think @Domenic has a better answer.


I was unsure about answering an old question however I stumbled across this while seeking an answer myself.

for (var i = 1; i < 11; i++) { // Creating 10 objects
window["Object"+i] = new Object();
}
console.log(Object7); // is not undefined

The above code loops to 10 while creating dynamic objects, as described on https://www.codecademy.com/en/forum_questions/51068e93f73ad4947a005629


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"

Tags:

Javascript