Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create variables dynamiccally in JavaScript

Tags:

javascript

I'm looking for a way to create variables dynamically in javascript

eg

I have a loop

for (i=0;i<15;i++){
}

now I need to create variables dynamically eg var "a"+i for eavh value in the loop. Is this possible and how?

like image 349
Elitmiar Avatar asked May 24 '10 09:05

Elitmiar


People also ask

Can I create dynamic variable in JavaScript?

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

What is a dynamic variable JavaScript?

Dynamic variables compute their own values by executing statements and logical expressions. A dynamic variable assigns itself the result of a calculation or operation. The dynamic variable types are dynamic string, dynamic number, and dynamic True/False (Boolean).

How do you create a variable in JavaScript?

To create a variable in JavaScript, use the let keyword. To be concise, we can combine the variable declaration and assignment into a single line: let message = 'Hello! '; // define the variable and assign the value alert(message); // Hello!


3 Answers

Since you are dealing with numeric, sequential variables — use an array.

var foo = [];
for (var i = 0; i < 15; i++) {
    foo[i] = something;
}
like image 135
Quentin Avatar answered Oct 05 '22 22:10

Quentin


If we presume that you will need several variables related to each iteration ([foo1,bar1], [foo2, bar2]...) then there are two approaches

Use arrays

var foo = [], bar = [];
foo[1] = "foo"; 
bar[1] = "bar";

Use an object

var myVars = {};
myVars["foo" + 1] = "foo";
myVars["bar" + 1] = "bar";

That last one could also be written as

 myVars.bar1 = "bar";

Do not use eval as some has suggested.

like image 35
Sean Kinsey Avatar answered Oct 05 '22 22:10

Sean Kinsey


To fulfill your exact requirement, I know only eval():

eval("varname"+i+" = 'Hello';");

on the other hand, you could consider using an array. Much cleaner: They don't clutter the global namespace, and you can order variables neatly in groups.

arrayname[i] = value;
like image 32
Pekka Avatar answered Oct 06 '22 00:10

Pekka