Question

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

Était-ce utile?

La solution

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]);

Autres conseils

You can get pretty close:

var a = [1, 2, 3];
var head = a.shift(); // a is [2, 3] now

The gotcha is that it mutates. You can do ´slice()´ before the operation if you want to preserve the original.

This probably isn't the answer you are looking for but it is the simplest way to achieve what you are looking for. You could try to wrap some of that into a function to tidy it up.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top