Friday, May 4, 2012

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?


Source: Tips4all

4 comments:

  1. There is, but in "new" 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 :)

    ReplyDelete
  2. try this:

    matches = ['12', 'watt'];
    [value, unit] = matches;

    ReplyDelete
  3. There is a experimental implementation of list() by PHPJS here:
    https://github.com/kvz/phpjs/blob/master/_experimental/array/list.js

    ReplyDelete
  4. Here's another way of accomplishing this:

    http://stackoverflow.com/a/9853132/675007

    ReplyDelete