我在 Angular 組件中有以下方法:
public mapInvoices(invoices: any[]): Record<string, any> {
return invoices.reduce((map, obj) => {
map[obj.letterType] = obj;
return map;
}, {});
}
當我為此組件運行單元測驗時,我遇到了以下問題:
APAUInvoicesDocumentsComponent ? should create
TypeError: Cannot read property 'reduce' of undefined
37 |
38 | public mapInvoices(invoices: any[]): Record<string, any> {
> 39 | return invoices.reduce((map, obj) => {
| ^
40 | map[obj.letterType] = obj;
41 | return map;
42 | }, {});
我可以通過為引數分配默認值來繞過這個問題,例如:
public mapInvoices(invoices: any[] = [])
但我想了解為什么會這樣。
uj5u.com熱心網友回復:
要回答您的問題,這是因為mapInvoices正在使用undefined引數呼叫。通過設定默認值,您實際上是在覆寫初始狀態。
public mapInvoices(invoices?: any[] = []) {}
mapInvoices(); // call bombs without a default value
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/427221.html
標籤:javascript 有角度的 打字稿
