zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Destructuring array by using object syntax

JavaScript object by Using Array syntax
2023-09-14 09:00:42 时间

Since arrays are objects, we can destructure their indexes to easily grab the first and last itmes

const bikes = ['bianchi', 'miele', 'miyata', 'benotto', 'panasonic']

// Grab the first and last item of an array with Object destructuring
const {length, 0: first, [length - 1]: last} = bikes;
console.log(first, last) // bianchi panasonic

You can use length inside destructuring to access the last item

 

You can use lengthto do calculation to access middle item:

const {length, [Math.floor(length / 2)]: middle} = bikes;
console.log(middle) // miyata