以ES6方式获取数组中的第一个和最后一个元素 [英] Get first and last elements in array, ES6 way

查看:1686
本文介绍了以ES6方式获取数组中的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

文档就是这样

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

现在有一种方法可以只使用Destructuring

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

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

我知道如何以其他方式获取第一个和最后一个元素,但我想知道es6是否可行

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

推荐答案

休息参数只能在末尾使用,而不能在销毁过程中的其他任何地方使用,因此它将无法按预期工作.

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

相反,您可以 destructor 确定属性(数组也是JS中的对象),例如,0表示第一个元素,最后一个元素的索引表示最后一个元素.

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.

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

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


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

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.

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

这篇关于以ES6方式获取数组中的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆