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

1
  • Oh, I never found that post on SO, Thank You! :) Commented Jun 26, 2015 at 1:14

1 Answer 1

0

Write it into an array or object

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

then

alert(arr['newvariable']);

or

alert(arr.newvariable);
Sign up to request clarification or add additional context in comments.

8 Comments

So, to access this variable do I just type in window['newvariable'] each time?
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'].
yes, that's it. basically usnig the 'newvariable' as an array (or object) key
Thank You! :) That explains it much better.
Why create an empty array to attach an arbitrary property? You can just use an object literal: var arr = {};
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.