Javascript left-hand assignment
Tagged Javascript, list, PHP
Wouldn’t it be great to do something like this in javascript:
function test(){
return ['first!', 'second!'];
}
[first, second] = test();
alert(first); // should say ‘first!’
alert(second); // should say ’second!’
I was inspired by the PHP list function. Funny enough it worked in Firefox and Opera, but Safari and IE failed this simple test. A bit disappointed I came up with a list() implementation in javascript:
// My list javascript implementation.
function list(variables, values, scope){
for(var i = 0; i < variables.length && i < values.length; i++){
(scope || this)[variables[i]] = values[i];
}
}
// Example usage:
list(['first','second'], test());
alert(first); // says 'first!'
alert(second); // says 'second!'
// Example explaining the scope argument.
var obj = {};
list(['first','second'], test(), obj);
alert('obj.first:'+obj.first); // says 'obj.first:first!'
alert('obj.second:'+obj.second); // says 'obj.second:second!'
The list function takes three arguments. The first argument is an array of variable names and the second one is an array of values. The values are mapped on the variable names. The variables are available in the passed scope (the third argument). The default scope is the ‘this’ scope. When you’re not familiar with the scope thingy, go read ‘Getting Funky With Scopes and Closures’ written by Mark Wubben.
oh my god dude, you’re sick! thanks!