Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring in JavaScript 1.7

JavaScript 1.7 allows for destructuring:

[a, b] = [1, 2] // var a = 1, b = 2;

Is there a way to get the rest of the array and head like: Clojure

(let [[head & xs] [1 2 3]] (print head xs)) ; would print: 1 [2 3]

Python

a, b* = [1, 2, 3]

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7#Using_JavaScript_1.7

like image 589
Justin Thomas Avatar asked Feb 05 '14 18:02

Justin Thomas


1 Answers

Is there a way to get the rest of the array and head in a destructuring assignment?

I don't think so. The spread operator seems to be supported since FF16 in array literals, but the harmony proposal does not yet cover destructuring assignments. If it did, it would look like

[a, ...b] = [1, 2, 3];

Update: ES6 does support this syntax, known as the "rest element" in an array destructuring pattern.

So until then, you will need to use a helper function:

function deCons(arr) {
    return [arr[0], arr.slice(1)];
}
[a, b] = deCons([1,2,3]);
like image 173
Bergi Avatar answered Sep 21 '22 15:09

Bergi