简体   繁体   English

JavaScript 1.7中的解构

[英]Destructuring in JavaScript 1.7

JavaScript 1.7 allows for destructuring: JavaScript 1.7允许解构:

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

Is there a way to get the rest of the array and head like: Clojure 有没有一种方法可以获取其余的数组并像这样:head

(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 参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/New_in_JavaScript/1.7#Using_JavaScript_1.7

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. 从FF16开始,数组文字中似乎支持散布运算符 ,但是和合提议尚未涵盖解构分配。 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. 更新 :ES6确实支持此语法,在数组解构模式中称为“其余元素”。

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

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. 如果要保留原始文件,可以在操作之前执行“ slice()”。

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. 您可以尝试将其中的一些包装到一个函数中进行整理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM