TypeError报错求助:Cannot read properties of null (reading 'length')
解决countPositivesSumNegatives函数的TypeError问题
报错原因
报错TypeError: Cannot read properties of null (reading 'length')是因为当传入的input为null时,你的代码跳过了初始判断,直接进入for循环尝试读取input.length,但null没有length属性,导致报错。同时代码未实现「输入[0,0]时返回空数组」的需求。
修正步骤与代码
1. 先处理null/undefined与空数组的情况
把初始判断改成先检查input是否为null或undefined,或者是空数组,满足任一条件直接返回空数组:
if (!input || input.length === 0) { return []; }
这里!input会覆盖input为null、undefined的情况,再加上空数组的判断,一次性处理这些边界场景。
2. 处理全0数组的情况
遍历数组后,需要判断统计结果是否全为0(即没有正数,负数和也为0),如果是则返回空数组,否则返回统计结果。
最终修正代码
function countPositivesSumNegatives(input) { let countPositive = 0; let sumNegative = 0; // 处理null、undefined、空数组的情况 if (!input || input.length === 0) { return []; } for (let i = 0; i < input.length; i++) { if (input[i] > 0) { countPositive++; } else if (input[i] < 0) { sumNegative += input[i]; } // 0的情况不做处理 } // 如果没有正数且负数和为0(说明数组全是0),返回空数组 if (countPositive === 0 && sumNegative === 0) { return []; } return [countPositive, sumNegative]; }
测试验证
- 输入
null→ 返回[] - 输入
[]→ 返回[] - 输入
[0,0]→ 返回[] - 输入
[1, -2, 3]→ 返回[2, -2] - 输入
[-1, -2, 0]→ 返回[0, -3]
内容的提问来源于stack exchange,提问作者zakarie mahmoud
相关产品推荐
相关产品推荐

