如何忽略数组解构的某些返回值? [英] How can I ignore certain returned values from array destructuring?
问题描述
当我只对索引 0 以外的数组值感兴趣时,是否可以避免在数组解构时声明无用的变量?
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
在下面,我想避免声明 a
,我只对索引 1 及以后感兴趣.
In the following, I want to avoid declaring a
, I am only interested in index 1 and beyond.
// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest);
推荐答案
当我只对索引 0 以外的数组值感兴趣时,是否可以避免在数组解构时声明无用的变量?
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
是的,如果您将作业的第一个索引留空,则不会分配任何内容.此行为在此处解释.
Yes, if you leave the first index of your assignment empty, nothing will be assigned. This behavior is explained here.
// The first value in array will not be assigned
const [, b, ...rest] = [1, 2, 3, 4, 5];
console.log(b, rest);
您可以在任何地方使用任意数量的逗号,除了在休息元素之后:
You can use as many commas as you like wherever you like, except after a rest element:
const [, , three] = [1, 2, 3, 4, 5];
console.log(three);
const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);
以下产生错误:
const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);
这篇关于如何忽略数组解构的某些返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!