Variable Variables in Javascript

Thursday Jun 14 2007

Today I was looking for a decent way to have variable variables in . Because I work with a whole bunch of particularly bright people*, the answer to any question is always near. I figured I'd share today's little insight! First let's look about how we'd do this in PHP:

Suppose you have a variable named $i containing a numeric value. In this example it's 1 but it could be anything. You want to create a new variable named name1. In PHP you'd use the double $ way:

  1. $i=1;
  2. ${'name'.$i} = 'Marco';
  3. echo "got ".$name1;

When doing the same thing in Javascript, the dreaded eval() comes to mind:

  1. var i=1;
  2. eval('name' + i + ' = "Marco"');
  3. document.write('got ' + name1);

Nasty. We don't want to use eval() if we can avoid it. And most of the time we actually can! Here's a much more proper way of doing it, using the fact that all global variables are held in the window array.

  1. var i=1;
  2. window['name' + i] = 'Marco';
  3. document.write('got ' + name1);

There we go! Nice, clean and no eval() necessary.

* It's absolutely delightful to work with people who all excel in what they do without the often associated 'arrogant prick attitude'. I love my job! =)

Dark Matter Pro: a premium photoblog template.

Affiliate program available

bookmarking

Commentary

Join the discussion! Leave a comment through the comment form below!

Got something to add to this?

Feel free to leave a comment on this site. You can use Textile and Emoticons. Your email address is only used to show a gravatar. Please stay on-topic and use common decency. Spammers will be shot in front of a live studio audience.

If you plan on posting code, use pastebin please and post a URL to the code. The comment processing doesn't deal very well with code. Sorry for the inconvenience.

Human comment spammers: don't bother posting your crap here. Comments are moderated and I won't let any of your shit through.

Remember personal info?
Yes
No

Trackbacks

If you have an interesting related post on your own site you can leave a trackback. As they say: 'a little AJAX a day keeps the spammers away' which is why you'll have to click below to generate a trackback key. The key will be valid for 15 minutes and can be used only once.

 

  • Featured Links
RockySomewhere near the Orion NebulaBookalicio.usGolden Gate BridgeThames River BankJackie and mePimpin' it