0

I know there are other questions similar to this, but I feel as if they don't answer my question. I would basically like to make Dynamic Variable Names. Let me give you an example:

//Take the strings "new" and "variable" and make them into a variable.
"new" + "variable" = "Hello World";
//So technically the variable name is "newvariable" and has the value "Hello World"

So basically it takes two strings, and combines them into one variable name. How would I go about doing this?

P.S. This is NOT to combine the values of variables, just the names

Michael Jones
  • 2,222
  • 18
  • 32

1 Answers1

0

Write it into an array or object

var arr = {};
arr['new' + 'variable'] = 'Hello World';

then

alert(arr['newvariable']);

or

alert(arr.newvariable);
hildende
  • 832
  • 1
  • 13
  • 19
  • So, to access this variable do I just type in `window['newvariable']` each time? – Michael Jones Jun 26 '15 at 01:14
  • Yes, but actually putting the variables into the `window` namespace isn't a good idea. Better create a new `vars[]` in that case, and then have `vars['newvariable']`. – tomasyany Jun 26 '15 at 01:15
  • yes, that's it. basically usnig the 'newvariable' as an array (or object) key – hildende Jun 26 '15 at 01:15
  • Thank You! :) That explains it much better. – Michael Jones Jun 26 '15 at 01:17
  • Why create an empty array to attach an arbitrary property? You can just use an object literal: `var arr = {};` – Brandon Jun 26 '15 at 01:20
  • So just to verify, something like this would be totally correct? `var dynamic["replyupvote" + String(replyid)] = false;` – Michael Jones Jun 26 '15 at 01:20
  • @hildende I am very confused right now. I am using this `dynamic["replyupvote"+replyid]` to write my variables, and it does not seem to be working. Any idea why? Thank You! :) *P.S. if you would like to see my full code it is here: **http://pastebin.com/tpS4pPtf*** – Michael Jones Jun 26 '15 at 01:49
  • You're using an array the way you'd use an object. It works, but it makes little sense. –  Jun 26 '15 at 02:11