箭头函数重构数组条件求和及toFixed(2)返回undefined问题排查
问题解答
问题2:toFixed(2)后返回undefined的修复
你的代码返回undefined有两个核心原因:
- main函数无返回值:函数内计算完
result后没有用return语句返回结果,调用main()自然会得到默认的undefined。 - 函数调用参数错误:你调用
main("_feeAmts", "_feeCategory", "_ovrFeeAmts", "_ovrFeeCategor")时传的是变量名字符串,不是实际的数组变量;而且最后一个参数拼写错误(_ovrFeeCategor少了末尾的y)。
另外,你定义的_feeAmtOne、_feeCategoryOne等变量未赋值,实际运行会报错,需要给它们赋具体的数值和类别字符串。
修复后的基础版代码:
function main(feeAmts, feeCategory, ovrFeeAmts, ovrFeeCategory) { let tmpTotalOne = 0; let tmpTotalTwo = 0; const otherFee = "OTHER FEE"; for (let ndx = 0; ndx < feeAmts.length; ndx += 1) { if (feeCategory[ndx].toUpperCase() === otherFee) { tmpTotalOne += feeAmts[ndx]; } } for (let ndx = 0; ndx < ovrFeeAmts.length; ndx += 1) { if (ovrFeeCategory[ndx].toUpperCase() === otherFee) { tmpTotalTwo += ovrFeeAmts[ndx]; } } const ttl = tmpTotalOne + tmpTotalTwo; return ttl.toFixed(2); // 关键:添加return返回计算结果 } // 给变量赋实际值示例 const _feeAmtOne = 10.5, _feeAmtTwo = 20.3, _feeAmtThree = 5.0; const _feeCategoryOne = "OTHER FEE", _feeCategoryTwo = "SERVICE FEE", _feeCategoryThree = "OTHER FEE"; const _ovrFeeAmtOne = 15.7, _ovrFeeAmtTwo = 8.2; const _ovrFeeCategoryOne = "OTHER FEE", _ovrFeeCategoryTwo = "ADMIN FEE"; // 修正参数:传实际变量,补全拼写错误 const result = main(_feeAmts, _feeCategory, _ovrFeeAmts, _ovrFeeCategory); console.log(result); // 现在会输出保留两位小数的字符串
问题1:用箭头函数重构代码
完全可以用箭头函数结合数组reduce方法重构,把重复的累加逻辑抽成复用的箭头函数,代码更简洁:
// 抽离通用的OTHER FEE累加逻辑为箭头函数 const calculateOtherFeeTotal = (amounts, categories) => amounts.reduce((total, amt, index) => categories[index].toUpperCase() === "OTHER FEE" ? total + amt : total, 0 ); // main函数也改成箭头函数 const main = (feeAmts, feeCategory, ovrFeeAmts, ovrFeeCategory) => { const totalOne = calculateOtherFeeTotal(feeAmts, feeCategory); const totalTwo = calculateOtherFeeTotal(ovrFeeAmts, ovrFeeCategory); return (totalOne + totalTwo).toFixed(2); }; // 变量赋值和调用(同修正版) const _feeAmts = [10.5, 20.3, 5.0]; const _feeCategory = ["OTHER FEE", "SERVICE FEE", "OTHER FEE"]; const _ovrFeeAmts = [15.7, 8.2]; const _ovrFeeCategory = ["OTHER FEE", "ADMIN FEE"]; const result = main(_feeAmts, _feeCategory, _ovrFeeAmts, _ovrFeeCategory); console.log(result); // 输出类似"31.20"的结果
重构说明:
- 用
reduce替代for循环,直接遍历数组并累加符合条件的金额 - 箭头函数
calculateOtherFeeTotal复用了两组费用的判断逻辑,消除代码冗余 - main函数改成箭头函数,进一步简化代码结构
内容的提问来源于stack exchange,提问作者Cooliozar
相关产品推荐
相关产品推荐

