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

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

问题描述:

当我只对索引0之外的数组值感兴趣时,我可以避免在数组解构时声明无用变量吗?如何忽略数组解构中返回的某些值?

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

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

 
console.log(a, b, rest);

+1

相关:[解构阵列获得第二值?](https://*.com/q/44559964/218196),[长期阵列对象解构溶液?](https://开头*.com/q/33397430/218196) –

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

,只要你喜欢你喜欢的地方,除了休息元素后,您可以使用尽可能多的逗号:

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