累加至负数停止:空数组for循环中索引0的使用及逻辑实现问题
Hey there! Let's break down your two questions and fix up your code to handle all cases correctly.
First, Let's Address Your Specific Questions
1. Handling Empty Arrays in the For Loop
Your current code actually handles empty arrays correctly by accident, but the check if (lenArr === 0) { break; } inside the loop is unnecessary. When the input array is empty, lenArr is 0, so the loop condition i <= lenArr -1 becomes 0 <= -1 — which is false. The loop never runs, and sum stays 0 (which is the correct return value for an empty array).
To make this cleaner, you can simplify the loop condition to i < lenArr instead of i <= lenArr -1 — it's the same logic but easier to read.
2. Returning 0 for a Single Negative Input
Your current code already does this correctly! Let's test it with input = [-5]:
lenArris 1, so the loop runs fori=0- The code checks
arr[i] > 0—-5 > 0is false, so it hits theelseclause and breaks the loop sumremains 0, which is returned. Perfect!
Now, Fix the Hidden Bug in Your Code
Wait a second — there's a mistake in your logic that you might not have noticed: your code only adds positive numbers, but your rule says to stop only when hitting a negative number. That means non-negative numbers (like 0) should be included in the sum!
For example, if you pass [0, 3, -2], your current code would return 0 (since it skips adding 0) instead of the correct value 3.
Revised Code with All Cases Handled
Here's the fixed version of your function, with cleaner logic and no bugs:
function runningSum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { const currentNum = arr[i]; // Stop immediately if we hit a negative number if (currentNum < 0) { break; } // Add non-negative numbers (positive or zero) to the sum sum += currentNum; } return sum; }
Logic Validation for All Test Cases
Let's test this revised code against all critical scenarios:
- Empty array:
runningSum([])returns 0 ✔️ - Single negative:
runningSum([-10])returns 0 ✔️ - Single positive:
runningSum([5])returns 5 ✔️ - Zero included:
runningSum([0, 2, -1])returns 2 ✔️ - Multiple positives then negative:
runningSum([1, 3, 5, -2, 4])returns 9 ✔️ - All non-negatives:
runningSum([2, 4, 6])returns 12 ✔️
This code covers every case you mentioned and fixes the oversight with non-positive (but non-negative) numbers.
内容的提问来源于stack exchange,提问作者Tobe Christopher

