仅用for循环计算银行账户取款总额:无取款账户返回0的问题
解决银行账户取款总额计算中的空值问题
问题描述
遍历给定的银行账户数组,返回各账户的取款总额组成的新数组;若账户无取款记录,则返回0。当前实现中,无取款记录的账户会返回空值,期望输出为[300.68,0,5900,0,100],实际输出为[300.68,,5900,,100]。
问题原因
你的代码中,当账户不存在withdrawals属性时,numbs为undefined,执行newArray.push(numbs||0)会将0存入newArray。但内层循环尝试遍历newArray[i].length,而0没有length属性,循环条件不成立,导致total[i]未被赋值,最终数组出现空元素。
修正方案
直接判断每个账户是否存在withdrawals数组,存在则计算总和,不存在则直接赋值0,无需中间数组newArray:
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] }, { id: 3, name: "Joshua", balance: 18456.57, deposits: [4000, 5000, 6000, 9200, 256.57], withdrawals: [1500, 1400, 1500, 1500], }, { id: 4, name: "Candy", balance: 0.0 }, { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] }, ]; function itsSomething(array) { const total = []; for (let i = 0; i < array.length; i++) { const account = array[i]; let sum = 0; // 检查当前账户是否有取款记录数组 if (account.withdrawals) { for (let x = 0; x < account.withdrawals.length; x++) { sum += account.withdrawals[x]; } } // 确保每个位置都被赋值,无取款记录时sum默认为0 total[i] = sum; } return total; } console.log(itsSomething(bankAccounts));
说明
- 无论账户是否有取款记录,都会给
total[i]赋值,避免空元素出现。 - 若
withdrawals存在但为空数组,内层循环不会执行,sum保持0,也能正确返回0。
内容的提问来源于stack exchange,提问作者Justin Hawkins
相关产品推荐
相关产品推荐

