JavaScript ES6:将数组拆分为rest并最后进行解构[duplicate]

时间:2021-10-27 21:20:55

This question already has an answer here:

这个问题在这里已有答案:

I just discovered the delightful ES6 destructuring syntax for lists, i.e.

我刚刚为列表发现了令人愉快的ES6解构语法,即

ls = [1, 2, 3]

[first, ...rest] = ls

which sets first to 1 and rest to [2,3]. However, is it possible to split the list into rest=[1,2] and last=3 using similar syntax?

首先设置为1,然后设置为[2,3]。但是,是否可以使用类似的语法将列表拆分为rest = [1,2]和last = 3?

I didn't have any luck googling it. I tried some obvious guesses for such a syntax (see below), but they all produced syntax errors.

我没有任何运气谷歌搜索它。我尝试了一些明显的语法猜测(见下文),但它们都产生了语法错误。

[rest..., last] = ls
[...rest, last] = ls

I suppose I could do it by reversing the list twice, so an alternate solution to my question would be a constant time list reversal function.

我想我可以通过两次反转列表来做到这一点,所以我的问题的另一个解决方案是一个恒定的时间列表反转功能。

2 个解决方案

#1


3  

What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:

通常所谓的“数组解构”实际上是对可迭代的解构,其中数组是一种特殊情况。关于iterables的事情是它们可以是无限的,或者是“懒惰的”。这就是你无法将最后一个元素解构为一些任意数量的元素的原因:

const [...first, last] = integers();

because integers could be

因为整数可能是

function* integers() {
  let n = 0;
  while (true) yield n++;
}

and then what would last be?

然后会是什么?

#2


0  

No, this only works on trailing array elements. So, as you said, they way to achieve what you want would be reversing the array first.

不,这仅适用于尾随数组元素。所以,正如你所说,他们实现你想要的方法首先是颠倒阵列。

Just in case you haven't come across a similar pattern for object, there is one:

万一你没有遇到类似的对象模式,有一个:

const {a, ...rest} = {a: "prop1", b: "prop2", c: "prop3"}

A great tool to try all this new features out is https://babeljs.io/repl

尝试所有这些新功能的好工具是https://babeljs.io/repl

#1


3  

What is commonly called "array destructuring" is actually destructuring an iterable, of which an array is a special case. The thing about iterables is that they can be infinite, or "lazy". That is the reason that you cannot destructure into some arbitrary number of elements followed by the last one:

通常所谓的“数组解构”实际上是对可迭代的解构,其中数组是一种特殊情况。关于iterables的事情是它们可以是无限的,或者是“懒惰的”。这就是你无法将最后一个元素解构为一些任意数量的元素的原因:

const [...first, last] = integers();

because integers could be

因为整数可能是

function* integers() {
  let n = 0;
  while (true) yield n++;
}

and then what would last be?

然后会是什么?

#2


0  

No, this only works on trailing array elements. So, as you said, they way to achieve what you want would be reversing the array first.

不,这仅适用于尾随数组元素。所以,正如你所说,他们实现你想要的方法首先是颠倒阵列。

Just in case you haven't come across a similar pattern for object, there is one:

万一你没有遇到类似的对象模式,有一个:

const {a, ...rest} = {a: "prop1", b: "prop2", c: "prop3"}

A great tool to try all this new features out is https://babeljs.io/repl

尝试所有这些新功能的好工具是https://babeljs.io/repl