Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Dynamically Creating Variables for Loops

Tags:

javascript

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..... 
like image 453
user763349 Avatar asked Jul 11 '11 01:07

user763349


People also ask

How do you dynamically name variables in a loop?

You can use eval() method to declare dynamic variables.

Can we create dynamic variable in JavaScript?

Use an Array of VariablesThe 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.

Are there for looping in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.

What is a dynamic variable?

In programming, a dynamic variable is a variable whose address is determined when the program is run. In contrast, a static variable has memory reserved for it at compilation time.


1 Answers

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

like image 80
Domenic Avatar answered Oct 14 '22 09:10

Domenic