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—likenull,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.
- Add a parameter check at the start of your function:
Uncaught TypeError: arr[i] is not a number
This pops up when your array has non-number values (like strings, objects, orNaN) 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.
- Filter or convert non-number elements during iteration:
Infinite Loop (Browser becomes unresponsive)
This is almost always due to a mistake in yourwhileloop condition—like forgetting to increment your counter variable. For example, if you havelet i = 0; while (i < arr.length) { ... }but never addi++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.
- Always verify your counter logic: Make sure each loop iteration moves the counter closer to ending the loop (e.g.,
二、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 → ReturnstruecalculateSums([-5, 2, 2])→ Positive sum = 4, Negative absolute sum = 5 → ReturnsfalsecalculateSums([0, 0, 0])→ Both sums are 0 → ReturnstruecalculateSums([10, -10])→ Sums are equal → Returnstrue
内容的提问来源于stack exchange,提问作者Lisa

