I found this approach, which isn't too bad (at least for my purposes):
function swap( swap_name_a, swap_name_b )
{
eval
(
"var swap_temp="+swap_name_a+";"
+ swap_name_a+"="+swap_name_b+";"
+ swap_name_b+"=swap_temp;"
);
}
You are required to quote the arguments:
swap('a','b');
It seems to also work with more complex arguments:
swap('list[index1]','list[index2]');
Note: You will need to implement the swap() function within each scope that it will be used because it must have access to the named arguments. This goes against the "don't-repeat-yourself" principal, but in some circumstances it may be acceptable to copy-and-paste a bit of boilerplate code like this if it results in simplification of your algorithm logic.
By the way: The example from which I derived this returned the string from swap() and relied on the caller to forward the string to eval: eval(swap('a','b'))
. This solves the scope problem, but makes the swap operation more error prone -- and less attractive.
Be careful, that source also warned that this method could result in taunting.
Will time-traveling space-vampires steal your credit cards if you use eval()
? You should decide that for yourself, but here's some help:
The biggest concern I see is that this might be relatively slow (depending on how the interpreter manages caching). If it is too slow for your purposes, then don't use it.