Javascript equivalent of PHP's list()
Really like that function.
$matches = array('12', 'watt');
list($value, $unit) = $matches;
Is there a Javascript equivalent of that?
Solution 1:
There is, in 'newer' versions of Javascript: Destructuring assignment - Javascript 1.7. It's probably only supported in Mozilla-based browsers, and maybe in Rhino.
var a = 1;
var b = 3;
[a, b] = [b, a];
EDIT: actually it wouldn't surprise me if the V8 Javascript library (and thus Chrome) supports this. But don't count on it either
Now supported in all modern browsers(except IE, of course).
Solution 2:
try this:
matches = ['12', 'watt'];
[value, unit] = matches;
Solution 3:
ES6 does support this directly now via array destructuring.
const matches = ['12', 'watt'];
const [value, unit] = matches;
Solution 4:
This is my solution for using List/Explode on Javascript. Fiddle Working Example
First the implementation :
var dateMonth = "04/15";
dateMonth.split("/").list("month","day", "year");
month == "04";
day == "15";
year == null;
It also allows for scoping the new generated variables :
var scoped = (function()
{
var dateMonth = "07/24/2013";
dateMonth.split("/").list("month","day", "year", this);
this.month == "07";
this.day == "24";
this.year == "2013";
})();
This was accomplished by modifying an the Array prototype.
Array.prototype.list = function()
{
var
limit = this.length,
orphans = arguments.length - limit,
scope = orphans > 0 && typeof(arguments[arguments.length-1]) != "string" ? arguments[arguments.length-1] : window
;
while(limit--) scope[arguments[limit]] = this[limit];
if(scope != window) orphans--;
if(orphans > 0)
{
orphans += this.length;
while(orphans-- > this.length) scope[arguments[orphans]] = null;
}
}