gpt4 book ai didi

javascript - 数组 'map' 与 'forEach' - 函数式编程

转载 作者:行者123 更新时间:2023-11-28 14:34:05 26 4
gpt4 key购买 nike

我有一个对象数组:

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

关于javascript - 数组 'map' 与 'forEach' - 函数式编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com