2

Possible Duplicate:
“Variable” Variables in Javascript?

I'm thinking surely there is a way to achieve dynamic or variable variables in JavaScript (jQuery) much as one might in php where we might have...

<?php
$params = array("street", "city", "state","zip_code");
foreach($params as $key) $$key = some_function($key);
echo $city; // would output the result of some_function(city);
?>

but I can't see a way to accomplish similar in jQuery (JavaScript) where I would like to have something like...

<script>
params =["street", "city", "state","zip_code"];
jQuery.each(params, function() {
    var var this = jQuery('#'+this).val();
});
alert(city);
</script>

Which (of course) doesn't work, but there must be a way?

Community
  • 1
  • 1
WallabyKid
  • 503
  • 2
  • 5
  • 16

2 Answers2

3

Using "variable variables" is never necessary in a language that doesn't suffer from PHP's limitations.

addr = {};
params =["street", "city", "state","zip_code"];
jQuery.each(params, function() {
    addr[this] = jQuery('#'+this).val();
});
alert(addr.city);

In Javascript, addr["city"] and addr.city refer to the same thing.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    PHP has the same array capabilities you are using with JavaScript. Variable variables are simply added flexibility. – Sam Becker Dec 30 '11 at 02:38
  • Okay. Cool... I kinda danced around something pretty similar, but your solution brings it into focus for me. Thanks Though like Sam152, I prefer to think of variable variables as a mode of flexibility – WallabyKid Dec 30 '11 at 02:40
  • It seems that simply calling the dynamically generated variable $city (in the 'limited' PHP scenario) is much cleaner/simpler than remembering later to call addr["city"] or addr.city in the javascript version. Just my 2 cents. – WallabyKid Dec 30 '11 at 02:47
  • Even in PHP variable variables are hardly *"necessary"*. The answer in PHP is to use an array, the same thing you're demonstrating here. – deceze Dec 30 '11 at 03:03
  • Dynamically generated variables make the code harder to compile (because the compiler can't know the names of all the variables that might exist at any given time), and slower to execute (because variable access has to look up by name instead of by index or something). – Greg Hewgill Dec 30 '11 at 03:06
0

Settled on the following (which is just a tad cleaner IMHO)

params =["street", "city", "state","zip_code"];
jQuery.each(params, function() {
    params[this] = jQuery('#'+this).val();
});
alert(params.city); // or params['city'];
WallabyKid
  • 503
  • 2
  • 5
  • 16