Javascript 获取数组中的第一个和最后一个元素,ES6 方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44527643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:35:29  来源:igfitidea点击:

Get first and last elements in array, ES6 way

javascriptarraysfunctionecmascript-6

提问by Nicholas

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] = arraywill output 1 and the rest of array

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

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

现在是有办法只有采取第一和最后一个元素1 & 0Destructuring

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 是否可行

回答by Pranav C Balan

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

其余的参数可以在最后没有任何其他地方的解构,这样就不会工作,如你预期只能使用。

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

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

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)