[英]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
然后,对于所有索引i
和j
, A[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.