[英]How can I ignore certain returned values from array destructuring?
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);
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);
Ignoring some returned values忽略一些返回值
You can use ',' ignore return values that you're not interested in:您可以使用 ',' 忽略您不感兴趣的返回值:
const [, b, ...rest] = [1, 2, 3, 4, 5];
console.log(b);
console.log(rest);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.