You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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]

问题原因

  1. 直接累加对象导致类型转换:reduce的currentValue是数组中的每个对象,你直接把它和数字previousValue相加时,JavaScript会把对象转换为字符串[object Object],之后的操作就变成了字符串拼接,所以得到了错误的结果。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:24:27