[Javascript] dynamic var names

Michael Borchers list at tridemail.de
Wed Aug 8 01:43:28 CDT 2007


> On Aug 7, 2007, at 3:18 PM, Troy III Ajnej wrote:
>
>> My understanding is that you are trying to asign a value to the value!
>
> Not exactly.  A dynamic variable name would assign a value to a  variable 
> with the name of a value.  It's a pretty obscure concept,  but in PHP, for 
> example, you can do this like so:
>
> $variableName = 'foo';
> ${ $variableName } = 'bar';
> print( $foo ); // outputs 'bar'
>
> I've only ever found that useful in two contexts, neither of which  appear 
> to apply here: 1) obfuscation (i.e. making code more confusing  than 
> necessary) and 2) meta-programming (i.e. writing another  programming 
> language within PHP).
>
> Peace,
> Scott

Hi Scott,
indeed this was my attempt. My work is based on php, that's why I thought 
about the
idea of doing it in javascript when I needed it.

The reason I do it - I needed a function like this:

var foo = '';
var bar = '';

function setTempValue(varName, varValue) {
    // Set the var given in the string varName to value varValue
}

setTempValue('foo', 1);

=> alert(foo) => 1 




More information about the Javascript mailing list