This is not intended for actual use in real life, just an interesting exercise. See Why use a JavaScript eval function as a bad idea? for details.
This is the closest thing you can get without resorting to vendor-specific extensions:
myArray = [1,2,3]; eval(set('a,b,c = myArray'));
Auxiliary function:
function set(code) { var vars=code.split('=')[0].trim().split(','); var array=code.split('=')[1].trim(); return 'var '+vars.map(function(x,i){return x+'='+array+'['+i+']'}).join(','); }
Proof that it works in an arbitrary area:
(function(){ myArray = [4,5,6]; eval(set('x,y,z = myArray')); console.log(y);
eval not supported in Safari.
ninjagecko Apr 24 '12 at 13:00 2012-04-24 13:00
source share