You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

累加至负数停止:空数组for循环中索引0的使用及逻辑实现问题

Fixing Your "Sum Until Negative" Function

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]:

  • lenArr is 1, so the loop runs for i=0
  • The code checks arr[i] > 0 — -5 > 0 is false, so it hits the else clause and breaks the loop
  • sum remains 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:02:33