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

JavaScript求和程序浏览器异常咨询及calculateSums函数实现求助

JavaScript求和程序异常排查与calculateSums函数实现

Hey folks, let's break down two key things here: fixing common browser errors in JavaScript sum programs, and building the calculateSums function exactly as you need it.

一、常见求和程序浏览器错误及解决建议

Let's walk through the most frequent issues you might hit and how to fix them:

  • Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    This usually happens when you're trying to work with something that's not an array—like null, undefined, or a plain object—instead of your intended number array. For example, if you accidentally pass a single number instead of an array, or your array variable wasn't initialized properly.
    Fixes:

    • Add a parameter check at the start of your function: if (!Array.isArray(arr)) throw new Error('Parameter must be an array of numbers');
    • Double-check the value you're passing to the function—make sure it's a valid array before calling the sum logic.
  • Uncaught TypeError: arr[i] is not a number
    This pops up when your array has non-number values (like strings, objects, or NaN) mixed in. Trying to add these to a sum will throw a type error.
    Fixes:

    • Filter or convert non-number elements during iteration: const num = Number(arr[i]); if (isNaN(num)) continue; (if you want to ignore invalid entries), or throw an error to alert the user that the array must contain only numbers.
    • Validate the array before processing: Use arr.every(item => typeof item === 'number') to ensure all elements are numbers.
  • Infinite Loop (Browser becomes unresponsive)
    This is almost always due to a mistake in your while loop condition—like forgetting to increment your counter variable. For example, if you have let i = 0; while (i < arr.length) { ... } but never add i++ inside the loop, it'll run forever.
    Fixes:

    • Always verify your counter logic: Make sure each loop iteration moves the counter closer to ending the loop (e.g., i++, index-- depending on your loop direction).
    • Debug with console.log(index) inside the loop to see if the counter is updating correctly.

二、calculateSums函数实现(符合while循环要求)

Here's the function that meets all your requirements: it uses a while loop, ignores 0 (since it doesn't affect the sum comparison), and returns true when the sum of positives is greater than or equal to the sum of absolute values of negatives.

function calculateSums(numbers) {
  // First, validate the input is an array
  if (!Array.isArray(numbers)) {
    throw new Error('Input must be an array of numbers');
  }

  let positiveSum = 0;
  let negativeAbsSum = 0;
  let index = 0;

  // Use while loop to iterate through the array
  while (index < numbers.length) {
    const current = numbers[index];
    
    // Skip non-number values (optional: you could throw an error instead)
    if (typeof current !== 'number' || isNaN(current)) {
      index++;
      continue;
    }

    if (current > 0) {
      positiveSum += current;
    } else if (current < 0) {
      // Add the absolute value of negative numbers
      negativeAbsSum += Math.abs(current);
    }
    // 0 is ignored since it doesn't impact either sum

    index++; // Don't forget to increment the counter!
  }

  // Compare the two sums and return the result
  return positiveSum >= negativeAbsSum;
}

Quick Test Cases

Let's verify it works as expected:

  • calculateSums([1, -2, 3]) → Positive sum = 4, Negative absolute sum = 2 → Returns true
  • calculateSums([-5, 2, 2]) → Positive sum = 4, Negative absolute sum = 5 → Returns false
  • calculateSums([0, 0, 0]) → Both sums are 0 → Returns true
  • calculateSums([10, -10]) → Sums are equal → Returns true

内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:59:39