如何使用 javascript 在 foreach() 中进行函数调用

我想知道如何使用 javascript 在 forEach() 中进行函数调用。


下面的函数工作正常,但由于 indoTransCalc和doFundCalc,计算是相似的,有没有其他方法可以做到这一点。


var objFund = [{

  "sucess": "true",

  "id": "fund",

  "options": "others",

  "fee": 3,

  "tax": 0.3,

  "amount": 2000

}]


var objTrans = [{

  "sucess": "true",

  "id": "trans",

  "options": "service",

  "fee": 2,

  "tax": 0.4,

  "amount": 1000

}]



function doTransCalc(trans) {

  trans.forEach(e => {

    if (e.success) {

      e.rate = 2.0,

        e.netFee = e.fee + e.tax,

        e.amountwithfee = e.amount + e.netfee,

        e.total = e.amountwithfee * e.rate;

    }

  })

}


function doFundCalc(fund) {

  fund.forEach(e => {

    if (e.success) {

      e.rate = 4.0,

        e.addfee = 10,

        e.netFee = e.fee + e.tax,

        e.amountwithfee = e.amount + e.netfee,

        e.total = e.amountwithfee * e.rate;

    }

  })

}


doTransCalc(objTrans);

doFundCalc(objFund);


console.log(objTrans);

console.log(objFund);


当年话下
浏览 381回答 3
3回答

斯蒂芬大帝

你可以用一个函数来完成,并用 ES6 特性调用你的列表。const fundList = [{  "success": "true",  "id": "fund",  "options": "others",  "fee": 3,  "tax": 0.3,  "amount": 2000},{  "success": "true",  "id": "fund",  "options": "others",  "fee": 3,  "tax": 0.3,  "amount": 2000}]const transList = [{  "success": "true",  "id": "trans",  "options": "service",  "fee": 2,  "tax": 0.4,  "amount": 1000},{  "success": "true",  "id": "trans",  "options": "service",  "fee": 2,  "tax": 0.4,  "amount": 1000}]function calc(e, rate, addFee) {  const netFee = e.fee + e.tax;  const amountwithfee = e.amount + netFee;  return {    rate: rate,    addfee: addFee ? addFee : null,    netFee,    amountwithfee,    total: amountwithfee * rate  }}const newTransList = transList.filter(e => e.success === 'true').map(e => calc(e, 2));console.log(newTransList);const newFundList = fundList.filter(e => e.success === 'true').map(e => calc(e, 4, 10));console.log(newFundList);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript