数组' map' vs' forEach' - 函数式编程

时间:2018-05-14 16:08:39

标签: javascript dictionary 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)

我开始学习函数式编程,并希望将它应用到我的代码中,我会采用第一种方法(一个循环),但是当我研究函数式编程时,我认为第二个是正确的方式(更清洁)但是,我不确定,什么是更便宜的操作?

3 个答案:

答案 0 :(得分:3)

如果您的最终目标是从对象中创建三个变量,则可以按如下方式使用对象解构。不需要循环。



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




答案 1 :(得分:1)

如果要复制数组,只需使用Array#slice0传递是可选的,因为它是默认的开始索引,因此您可以省略它,如:)

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

答案 2 :(得分:0)

你基本上做的是矩阵换位:

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

话虽如此,你的第二种方法是恕我直言,最具可读性。