javascript – 如何忽略数组解构中的某些返回值?
作者:互联网
当我只对索引0之外的数组值感兴趣时,我可以避免在数组解构时声明无用的变量吗?
在下面,我想避免声明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?
是的,如果您将作业的第一个索引留空,则不会分配任何内容.此行为是explained here.
// The first value in array will not be assigned
const [, b, ...rest] = [1, 2, 3, 4, 5];
console.log(b, rest);
除了rest元素之外,您可以随意使用任意数量的逗号:
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);
标签:destructuring,javascript,arrays 来源: https://codeday.me/bug/20191007/1866219.html