JS函数totalTransactions计算交易总额返回错误值求修正
问题排查与修正
你的代码存在几个关键错误,导致返回结果不符合预期:
错误使用
for...in遍历数组for...in用于遍历对象的属性名,遍历数组时返回的是字符串类型的索引(比如"0"、"1"),而非数组中的交易对象。你把这些索引当作金额累加,结果自然错误。未正确获取交易对象的
amount属性
即便遍历到数组元素,你也没有从每个交易对象中取出实际的amount值,而是直接使用了遍历变量,完全没拿到目标金额。逻辑判断偏离需求
if (amount > 0)的判断对象错误,应该判断交易对象的amount是否为正,而非遍历得到的索引值。
修正后的代码方案
方案1:for...of遍历(直观易懂)
for...of专门用于遍历数组等可迭代对象,能直接获取每个交易对象:
function totalTransactions(transactions) { let total = 0; for (const transaction of transactions) { if (transaction.amount > 0) { total += transaction.amount; } } return total; }
方案2:数组reduce方法(简洁高效)
reduce是处理累加场景的常用数组方法,一行代码即可完成逻辑:
function totalTransactions(transactions) { return transactions.reduce((total, transaction) => { return transaction.amount > 0 ? total + transaction.amount : total; }, 0); }
方案3:forEach遍历(写法灵活)
逻辑和for...of一致,只是写法不同:
function totalTransactions(transactions) { let total = 0; transactions.forEach(transaction => { if (transaction.amount > 0) { total += transaction.amount; } }); return total; }
注意:你的示例中调用的是lastFridayNight(transactions),但函数定义名为totalTransactions,需保持函数名一致,否则会触发未定义错误。
内容的提问来源于stack exchange,提问作者Cluff3rs
相关产品推荐
相关产品推荐

