2017-10-16 54 views
0

當我只對索引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://stackoverflow.com/q/44559964/218196),[長期陣列對象解構溶液?](https://開頭stackoverflow.com/q/33397430/218196) –

回答

2

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