Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a variable to another variable in JavaScript?

I am running a loop, and I am trying to create a variable each time the loop runs with the number of the counter appended to the end of the variable name.

Here's my code:

var counter = 1;
while(counter < 4) {
  var name+counter = 5;
  counter++;
}

So after the loop runs there should be 3 variables named name1, name2, and name3. How can I append the counter number to the end of the variable I am creating in the loop?

like image 721
zeckdude Avatar asked Sep 04 '26 11:09

zeckdude


1 Answers

You're looking for an array:

var names = Array();
// ...
names[counter] = 5;

Then you will get three variables called names[0], names[1] and names[2]. Note that it is traditional to start with 0 not 1.

like image 147
Mark Byers Avatar answered Sep 07 '26 01:09

Mark Byers