0

For example A = 10, i want to create a variable with the value in it.

Like this: var i10 or if A = 2, i wanna create a variable like this var i2.

For e.g. A = 10 and B = 5, i want a var A10B5, is that possible?

Edit: more information

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
abcd1234123123
  • 117
  • 1
  • 3
  • 10

5 Answers5

3

It is possible, as explained in detail in this question on SO.

A = 10;
B = 5;

window['A' + A + 'B' + B] = 'Hello';

alert(A10B5);
// alerts: Hello

See a demo in this jsfiddle.

I don't see the point of it though though, since you have to keep a reference of the name of this object it's easier to store the value in a local variable inside a function or object that has always the same name or use an array to store the value.

Proposed solution for the intended use:

Use a two-dimensional array:

Calendar[A][B] = 'value';

By creating dynamic variables you will have to rebuild the name of the variable every time you need to access it it. By using a two-dimensional array you can just use the array with both variables, that spares you the code to rebuild the variable name over and over again and makes it easier to read and maintain.

Community
  • 1
  • 1
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
1
var A = 10, B = 5;
window['A' + A + 'B' + B] = "You should avoid polluting global " + 
                            "scope at all costs.";
alert(A10B5);

Instead you should resort to objects:

var myVars = {}, A = 10, B = 5;
myVars['A' + A + 'B' + B] = "Just like this.";
alert(myVars.A10B5);
sanmai
  • 29,083
  • 12
  • 64
  • 76
1

You can create dynamic variables with eval() function

var a = 10;
eval("variable" + a + " = a");

this return a variable with name "variable10" and value "10".

Take a look here too!

For more information: w3schools eval()

Hope it helps ^_^

Alesanco
  • 1,840
  • 1
  • 11
  • 13
0

You can have A = 10 and B = A which takes the same amount in a different variable, however, you also can make an if statement like

if(A > 10){ A = 11 } 
no name
  • 7
  • 7
0

check this out

`a = 'varname';

str = a+' = '+'123';

eval(str);

alert(varname); `

Community
  • 1
  • 1
Ankit Tyagi
  • 2,381
  • 10
  • 19
  • You provide a link to a good solution and accompany it with an example of a completely different, unrelated (and possibly dangerous) example? – Gerald Schneider Aug 02 '13 at 08:18