[Javascript] dynamic var names

Robert Van Dam rvandam00 at gmail.com
Wed Aug 8 21:37:34 CDT 2007


On 8/7/07, Michael Borchers <list at tridemail.de> wrote:
>
>
> I dynamically create a name for a var, let's say
>
> var myDynVar    = 'foo';
>
> Now I want to fill (var) foo with a value f.e. 'bar', so the next time I
>
> alert(foo)    results in => bar;
>
> I tried several combinations with eval() but still didn't get it. Can anyone
> help?
>

I'll second the previous comment that you should stay away from eval.
Objects can almost always do what you want here.  But just for the
sake of completeness, you can do you what you want like this:

var myDynVar = 'foo'
eval( myDynVar + " = 'bar'" );
alert(foo);

will alert 'bar' and not give an error.  Now that I said it, carefully
consider whether or not you really need it because it makes your code
very difficult to follow.

Rob



More information about the Javascript mailing list