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

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

在下面的内容中,我想避免声明 a,我只对索引1及以后的内容感兴趣。

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


console.log(a, b, rest);

20236 次浏览

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);

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);