簡體   English   中英

數組'map'與'forEach'-函數式編程

[英]Array 'map' vs 'forEach' - functional programming

我有一個對象數組:

let reports = [{ inbound_calls: [...], outbound_calls: [...],  outbound_national_calls: [...] },...];

創建新數組並將其分配給變量的最佳方法是什么:

第一種方法-一個循環:

let inbound_calls = []; outbound_national_calls = [], outbound_calls = [];

reports.forEach((e) => {
 inbound_calls.push(e.inbound_calls);
 outbound_national_calls.push(e.outbound_national_calls);
 outbound_calls.push(e.outbound_calls);
})

第二種方法:

let inbound_calls = this.reports.map((report) => report.inbound_calls)
let outbound_national_calls = this.reports.map((report) => report.outbound_national_calls)
let outbound_calls = this.reports.map((report) => report.outbound_calls)

我開始學習函數式編程,並想將其應用到我的代碼中,我會采用第一種方法(一個循環),但是當我對函數式編程進行研究時,我認為第二種方法是正確的方法(更簡潔)但是,我不確定什么是更便宜的手術?

如果最終目標是在對象之外創建三個變量,則可以按以下方式使用對象分解。 無需循環。

 let reports = { inbound_calls: [1, 2, 3], outbound_calls: [4, 5, 6], outbound_national_calls: [7, 8, 9] }; let {inbound_calls, outbound_calls, outbound_national_calls} = reports; console.log(inbound_calls); console.log(outbound_calls); console.log(outbound_national_calls); 

如果要復制陣列,只需使用Array#slice (傳遞的0是可選的,因為它是默認的起始索引,因此您可以根據需要省略它),例如:

let inbound_calls = reports.inbound_calls.slice(0),
    outbound_national_calls = reports.outbound_national_calls.slice(0), 
    outbound_calls = reports.outbound_calls.slice(0);

Array.from一樣:

let inbound_calls = Array.from(reports.inbound_calls),
    outbound_national_calls = Array.from(reports.outbound_national_calls), 
    outbound_calls = Array.from(reports.outbound_calls);

您實際上要做的是矩陣轉置:

 const report = (inbound_calls, outbound_calls, outbound_national_calls) => ({ inbound_calls, outbound_calls, outbound_national_calls }); const reports = [report(1,2,3), report(4,5,6), report(7,8,9)]; const transpose = reports => report( reports.map(report => report.inbound_calls) , reports.map(report => report.outbound_calls) , reports.map(report => report.outbound_national_calls) ); console.log(transpose(reports)); 

現在,根據您的應用程序,轉置矩陣的最快方法可能是根本不轉置矩陣。 例如,假設您有一個矩陣A及其轉置B 然后,對於所有索引ijA[i][j] = B[j][i] 考慮:

 const report = (inbound_calls, outbound_calls, outbound_national_calls) => ({ inbound_calls, outbound_calls, outbound_national_calls }); const reports = [report(1,2,3), report(4,5,6), report(7,8,9)]; // This is equivalent to transpose(reports).outbound_calls[1] const result = reports[1].outbound_calls; console.log(result); 

話雖如此,您的第二種方法是恕我直言,最易讀。

暫無
暫無

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

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