[Javascript] Destructuring array by using object syntax

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

 

posted @ 2022-12-25 19:59  Zhentiw  阅读(15)  评论(0编辑  收藏  举报