Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
当我只对索引0之外的数组值感兴趣时,我可以避免在数组解构时声明无用变量吗?
In the following, I want to avoid declaring a
, I am only interested in index 1 and beyond.
在下面,我想避免声明a,我只对索引1及更高版本感兴趣。
// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest);
1 个解决方案
#1
14
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
当我只对索引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:
您可以随意使用任意数量的逗号,除非在rest元素之后:
const [, , three] = [1, 2, 3, 4, 5];
console.log(three);
const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);
The following produces an error:
以下产生错误:
const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);
#1
14
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
当我只对索引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:
您可以随意使用任意数量的逗号,除非在rest元素之后:
const [, , three] = [1, 2, 3, 4, 5];
console.log(three);
const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);
The following produces an error:
以下产生错误:
const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);