My airbnb styleguide told me I should use Array Destructuring for the assignment below.
const splittedArr = [1, 2, 3, 4, 5]
const result = splittedArr[1];
So I wrote it like this using skipping values , to get the second element.
const splittedArr = [1, 2, 3, 4, 5]
const [, result] = splittedArr;
const splittedArr = [1, 2, 3, 4, 5] const result = splittedArr[1]; const [, res] = splittedArr; console.log(result, res);
But for instance when I have a higher indice to destruct
const splittedArr = [1, 2, 3, 4, 5]
const result = splittedArr[5];
This would mean I have to write it like
const splittedArr = [1, 2, 3, 4, 5]
const [,,,, result] = splittedArr;
const splittedArr = [1, 2, 3, 4, 5] const result = splittedArr[4]; const [, , , , res] = splittedArr; console.log(result, res);
Question: Is there a better way to write Array Destructuring with skipping values in JavaScript?
You could treat the array as object and destructure with the index as key and assign to a new variable name .
const array = [37, 38, 39, 40, 41, 42, 43], { 5: result } = array; console.log(result);
Use object-destructuring
instead:
const splittedArr = [1, 2, 3, 4, 5]; const { 1: second, 4: fifth } = splittedArr; console.log(second, fifth);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.