仅使用for循环找出余额最低且非零的银行账户(无正余额返回空数组)
问题:找出余额最低的有效银行账户
我正在完成一道仅允许使用for循环迭代的编程练习题,要求如下:
- 找出所有银行账户中余额最低的账户
- 若所有账户余额均不大于0,则返回空数组
以下是我编写的代码,但无法得到预期输出:
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 3.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: 10.0 }, { id: 5, name: "Phil", balance: 18.0, deposits: [100, 18], withdrawals: [100] }, ]; function itsSomething(array){ // Your code goes here... let min = 0; let minMin =[]; for (let i = 0; i < array.length; i++){ if (array[0].balance > array[i].balance && array[i].balance >0 ){ min = array[i] }else if ( array[i].balance > array[0].balance && array[0].balance > 0 ){ min = array[0] }else if ( array[i].balance && array[0].balance < 0 ){ min = [] } } return min } console.log(itsSomething(bankAccounts))
预期输出:
{ id: 2, name: "Morgan", balance: 3.0, deposits: [1100] }
代码问题分析
- 初始值错误:
let min = 0把数字0作为初始最小值,而我们需要跟踪的是账户对象,且0本身不属于有效账户(题目要求余额>0) - 比较逻辑局限:所有判断都只和
array[0]对比,无法遍历整个数组找到真正的最小值,比如当后续出现比第一个账户余额更小的有效账户时,无法正确更新结果 - 无效场景处理不当:判断所有账户余额不大于0的逻辑错误,仅通过
array[0]的余额判断,会导致误判其他有效账户的情况
修正后的代码
const bankAccounts = [ { id: 1, name: "Susan", balance: 100.32, deposits: [150, 30, 221], withdrawals: [110, 70.68, 120], }, { id: 2, name: "Morgan", balance: 3.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: 10.0 }, { id: 5, name: "Phil", balance: 18.0, deposits: [100, 18], withdrawals: [100] }, ]; function findLowestBalanceAccount(array) { // 第一步:筛选所有余额大于0的有效账户 let validAccounts = []; for (let i = 0; i < array.length; i++) { if (array[i].balance > 0) { validAccounts.push(array[i]); } } // 无有效账户则返回空数组 if (validAccounts.length === 0) { return []; } // 初始化最低账户为第一个有效账户 let lowestAccount = validAccounts[0]; // 遍历剩余有效账户,更新最低账户 for (let i = 1; i < validAccounts.length; i++) { if (validAccounts[i].balance < lowestAccount.balance) { lowestAccount = validAccounts[i]; } } return lowestAccount; } console.log(findLowestBalanceAccount(bankAccounts));
说明
- 先通过for循环筛选出所有余额>0的账户,避免无效数据干扰后续逻辑
- 检查有效账户数量,为空直接返回空数组,完全符合题目要求
- 从第一个有效账户开始,遍历后续账户逐一比较,确保找到余额最低的账户
- 全程仅使用for循环迭代,满足题目限制
内容的提问来源于stack exchange,提问作者Justin Hawkins
相关产品推荐
相关产品推荐

