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.....
You can use eval() method to declare dynamic variables.
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.
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.
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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With