本文介绍了数组解构跳过值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 airbnb样式指南告诉我,对于
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);
问题:是否有更好的方法用JavaScript中的跳过值来编写数组解构?
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);
这篇关于数组解构跳过值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!