获取数组中的第一个和最后一个元素,ES6方式[重复]

时间:2021-10-19 01:43:34

This question already has an answer here:

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

let array = [1,2,3,4,5,6,7,8,9,0]

let array = [1,2,3,4,5,6,7,8,9,0]

Documentation is something like this

文档是这样的

[first, ...rest] = array will output 1 and the rest of array

[first,... rest] =数组将输出1和数组的其余部分

Now is there a way to take only the first and the last element 1 & 0 with Destructuring

现在有一种方法只采用Destructuring的第一个和第一个元素1和0

ex: [first, ...middle, last] = array

例如:[first,... middle,last] = array

I know how to take the first and last elements the other way but I was wondering if it is possible with es6

我知道如何以另一种方式获取第一个和最后一个元素,但我想知道是否可以使用es6

1 个解决方案

#1


8  

The rest parameter can only use at the end not anywhere else in the destructuring so it won't work as you expected.

rest参数最后只能用于解构中的其他任何位置,因此它不会像预期的那样工作。

Instead, you can destructor certain properties(an array is also an object in JS), for example, 0 for first and index of the last element for last.

相反,您可以析构某些属性(数组也是JS中的对象),例如,0表示第一个,最后一个元素的索引表示最后一个。

let array = [1,2,3,4,5,6,7,8,9,0]

let {0 : a ,[array.length - 1] : b} = array;
console.log(a, b)

Or its better way to extract length as an another variable and get last value based on that ( suggested by @Bergi) , it would work even there is no variable which refers the array.

或者更好的方法是将长度作为另一个变量提取并根据它获得最后一个值(由@Bergi建议),即使没有引用数组的变量也可以工作。

let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)

#1


8  

The rest parameter can only use at the end not anywhere else in the destructuring so it won't work as you expected.

rest参数最后只能用于解构中的其他任何位置,因此它不会像预期的那样工作。

Instead, you can destructor certain properties(an array is also an object in JS), for example, 0 for first and index of the last element for last.

相反,您可以析构某些属性(数组也是JS中的对象),例如,0表示第一个,最后一个元素的索引表示最后一个。

let array = [1,2,3,4,5,6,7,8,9,0]

let {0 : a ,[array.length - 1] : b} = array;
console.log(a, b)

Or its better way to extract length as an another variable and get last value based on that ( suggested by @Bergi) , it would work even there is no variable which refers the array.

或者更好的方法是将长度作为另一个变量提取并根据它获得最后一个值(由@Bergi建议),即使没有引用数组的变量也可以工作。

let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)