簡體   English   中英

如何忽略數組解構中的某些返回值?

[英]How can I ignore certain returned values from array destructuring?

當我只對索引 0 以外的數組值感興趣時,我可以避免在數組解構時聲明一個無用的變量嗎?

在下文中,我想避免聲明a ,我只對索引 1 及以上感興趣。

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

當我只對索引0之外的數組值感興趣時,我可以避免在數組解構時聲明無用的變量嗎?

是的,如果您將作業的第一個索引留空,則不會分配任何內容。 此處解釋了此行為。

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

忽略一些返回值

您可以使用 ',' 忽略您不感興趣的返回值:

const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b);
console.log(rest);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM