JavaScript reduce统计数字数组元素次数报错,请求问题排查
问题:使用reduce统计数字数组元素出现次数时报错
我练习JavaScript的reduce函数时,用它统计对象数组中age属性的出现次数,代码能正常运行:
const users = [ { f: "aks", l: "shaini", age: 26 }, { f: "donald", l: "trump", age: 75 }, { f: "elon", l: "musk", age: 50 }, { f: "deepika", l: "padukone", age: 26 }, ]; const output = users.reduce((acc, curr) => { if (acc[curr.age]) { acc[curr.age] = ++acc[curr.age]; } else { acc[curr.age] = 1; } return acc; }, {}); console.log(output);
输出结果:{26: 2, 50: 1, 75: 1}
但用同样逻辑统计纯数字数组元素的出现次数时,代码报错:
function findOdd(A) { if (A.length === 1) return A[0]; const output = A.reduce((acc, curr) => { if (acc[curr]) { acc[curr] = ++acc[curr]; } else { acc[curr] = 1; } }, {}); return output; } console.log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]));
报错信息:
index.js:21 Uncaught TypeError: Cannot read properties of undefined (reading '1') at index.js:21:12 at Array.reduce (<anonymous>) at findOdd (index.js:20:20) at index.js:30:13
问题原因
核心问题是你写的第二个reduce回调函数没有返回累加器acc。
reduce的工作逻辑是:每一次迭代都会把回调函数的返回值作为下一次迭代的acc使用。第一个对象数组的代码里,最后明确写了return acc,所以每次迭代都能正确传递累加器;但第二个数字数组的reduce回调里,没有这个return语句,默认返回undefined,到第二次迭代时acc就变成了undefined,此时访问acc[curr]自然就会抛出“无法读取undefined的属性”的错误。
修正后的代码
只需要在reduce的回调函数末尾加上return acc即可:
function findOdd(A) { if (A.length === 1) return A[0]; const output = A.reduce((acc, curr) => { if (acc[curr]) { acc[curr] = ++acc[curr]; } else { acc[curr] = 1; } // 加上这行返回累加器 return acc; }, {}); return output; } console.log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]));
运行后就能得到正确的统计结果:{20: 2, 1: 2, -1: 2, 2: 2, -2: 2, 3: 2, 5: 3, 4: 2}
内容的提问来源于stack exchange,提问作者lucky
相关产品推荐
相关产品推荐

