抽离导出计算函数后调用报Cannot read properties of undefined (reading 'reduce')错误
问题原因排查
- 直接报错原因是你在
getStandardDeviation函数中调用getAverageScores时没有传入必填的data参数:getAverageScores函数需要接收数组类型的data参数才能调用reduce方法,空传参数的情况下函数内部的data值为undefined,调用undefined.reduce就会抛出你遇到的TypeError: Cannot read properties of undefined (reading 'reduce')错误。 - 额外的潜在问题:
getStandardDeviation中reduce回调的参数名和外层的data重名,虽然不会直接导致报错,但容易引发后续逻辑混淆,建议修改为更语义化的名称比如item。
修复方案
首先修改getStandardDeviation函数的调用逻辑,补全参数同时调整参数命名:
export const getStandardDeviation = (data) => { const total = 0; // 补全传入data参数 const averageScore = getAverageScores(data) // 回调参数改名避免和外层data重名 const squaredDeviations = data.reduce((acc, item) => { const deviation = item && item.value - averageScore; const deviationSquared = deviation * deviation; return acc + deviationSquared; }, total); return Math.sqrt(squaredDeviations / data.length); }
可选优化建议
你可以给两个工具函数加上参数合法性校验,避免后续调用时误传空值、非数组值引发异常:
const getAverageScores = (data) => { // 提前校验参数合法性 if (!Array.isArray(data) || data.length === 0) return 0; return data.reduce((acc, {value}) => acc + value, 0) / data.length; }
内容的提问来源于stack exchange,提问作者your uncle
相关产品推荐
相关产品推荐

