如何忽略数组解构中的某些返回值?

Kev*_*Bot 33 javascript arrays destructuring

当我只对索引0之外的数组值感兴趣时,我可以避免在数组解构时声明无用的变量吗?

在下面,我想避免声明a,我只对索引1及更高版本感兴趣.

// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];

console.log(a, b, rest);
Run Code Online (Sandbox Code Playgroud)

Kev*_*Bot 55

当我只对索引0之外的数组值感兴趣时,我可以避免在数组解构时声明无用的变量吗?

是的,如果您将作业的第一个索引留空,则不会分配任何内容.此处解释了此行为.

// The first value in array will not be assigned
const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b, rest);
Run Code Online (Sandbox Code Playgroud)

除了rest元素之外,您可以随意使用任意数量的逗号:

const [, , three] = [1, 2, 3, 4, 5];
console.log(three);

const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);
Run Code Online (Sandbox Code Playgroud)

以下产生错误:

const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);
Run Code Online (Sandbox Code Playgroud)