0

This is more of a syntax question, but I couldn't quite google it properly.

Say I have 2 variables:

classHours = 127;
currentNumber = 3;

How would I NAME a variable based off these numbers?

So let's say I wanted a variable named

classHours + "pop_up" + currentNumber 

How would I go about that?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Felix
  • 2,532
  • 5
  • 37
  • 75
  • 4
    There are ways to do that, but they are not common accepted practice in JavaScript. What problem are you trying to solve by doing this? There are other more idiomatic ways of creating and accessing lists and maps of values. – Pointy Oct 20 '14 at 15:10
  • 3
    Typically whenever you think you need to do something like this, you'd use arrays or objects instead. – JJJ Oct 20 '14 at 15:12
  • yes, @Pointy and Juhana are right. Try to searhc on `dynamic variable name`, or `variable variable name in javascript`. http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – vaso123 Oct 20 '14 at 15:13
  • May that help you : http://stackoverflow.com/a/26020014/2324107 – Karl-André Gagnon Oct 20 '14 at 15:13

2 Answers2

2

First, your variable can't start with a numerical digit, only letters and certain special characters. I believe what you want to do is set a global variable and you can do that by using the window object. What i would recommend is creating your own object variable and using that instead. This is how you would do that:

var infoObject = {
  classHours: 127,
  currentNumber: 3
}
infoObject['pop_up'+infoObject.classHours+'_'+infoObject.currentNumber] = 'variable contents here';

However, there should normally be no reason to have to create variables in this way. What exactly are you trying to accomplish?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jonathan Gray
  • 2,509
  • 15
  • 20
0

You could use an array with your dynamic variables, like this:

var dynamicVariables = [];

classHours = 127;
currentNumber = 3;

dynamicVariables[classHours + "pop_up" + currentNumber] = "Hey!";

alert(dynamicVariables["127pop_up3"]);  // => Hey!
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28