React中使用reduce计算对象数组总练习数出错求助
解决React中计算练习总数的错误问题
你的代码场景
App.js中的代码:
const course = { id: 1, name: "Half Stack application development", parts: [ { name: "Fundamentals of React", exercises: 10, id: 1, }, { name: "Using props to pass data", exercises: 7, id: 2, }, { name: "State of a component", exercises: 14, id: 3, }, { name: "Redux", exercises: 11, id: 4, }, ], }; return <Course course={course} />;
你编写的计算总数的代码:
const parts = props.Course.parts; const total = parts.reduce((previousValue, currentValue) => { return previousValue + currentValue; }, 0);
得到的错误输出:
0[object Object][object Object][object Object][object Object]
问题原因
- 直接累加对象导致类型转换:
reduce的currentValue是数组中的每个对象,你直接把它和数字previousValue相加时,JavaScript会把对象转换为字符串[object Object],之后的操作就变成了字符串拼接,所以得到了错误的结果。 - props属性名大小写不匹配:你传递的props是
course={course}(小写c),但代码里写的是props.Course(大写C),这会导致parts获取失败,这个笔误需要修正。
正确代码
// 修正props属性名大小写,和传递的参数一致 const parts = props.course.parts; // 累加每个对象的exercises属性值 const total = parts.reduce((prev, curr) => { return prev + curr.exercises; }, 0);
执行这段代码后,total的值会是10+7+14+11=42,符合预期。
内容的提问来源于stack exchange,提问作者user11877521
相关产品推荐
相关产品推荐

