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?
2 Answers 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?
Comments
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!
dynamic variable name, orvariable variable name in javascript. stackoverflow.com/questions/5117127/…