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

JavaScript数组对象姓名分数累加:生成总分映射对象求助

分数累加逻辑错误修复

我被这个分数累加问题卡了好几个小时,试了各种方法要么返回NaN,要么结果完全不对。示例输入如下:

// Example 1:
let ppl = [
  {name: "Anthony", score: 10},
  {name: "Fred", score : 10},
  {name: "Anthony", score: -8},
  {name: "Winnie", score: 12}
];

我的代码没法对重复姓名的分数做累加:

function countScores(people) {
  let scoreCount = {};
  
  people.forEach(person => {  // 遍历人员列表
    let name = person.name; // 获取姓名
    let score = person.score // 获取分数

    if (scoreCount[name]) {  // 检查姓名是否已存在,尝试累加分数
      scoreCount[score] += person.score;
      console.log("Am I being accessed???")
    }

    score = Number(person.score);   // 转换分数为数字
    name = person.name;      // 再次获取姓名
    console.log(name, score);
    
    scoreCount[name] = score;
  })

  console.log(scoreCount)
  console.log("Endig Calculation of Scores....")
  return scoreCount;
};

运行结果和预期不符:

+ expected - actual

       {
      -  "Anthony": -8
      +  "Anthony": 2
         "Fred": 10
         "Winnie": 12
       }

问题根源

  1. 累加键名错误:if分支里写的scoreCount[score] += person.score完全搞错了键名,应该用姓名name作为键,而不是当前分数score,否则根本没操作到对应姓名的条目。
  2. 结果被强制覆盖:不管if分支有没有执行,最后都执行scoreCount[name] = score,直接把之前的累加结果覆盖成当前分数——这就是Anthony的结果是-8而不是2的原因,最后一次赋值冲掉了之前的累加值。
  3. 初始值缺失:如果姓名第一次出现,scoreCount[name]是undefined,直接累加会得到NaN,需要先初始化值为0。

修复后的代码

function countScores(people) {
  const scoreCount = {};
  
  people.forEach(person => {
    const name = person.name;
    const score = Number(person.score); // 提前统一转数字,避免类型问题

    // 存在则累加,不存在则初始化
    if (scoreCount.hasOwnProperty(name)) {
      scoreCount[name] += score;
    } else {
      scoreCount[name] = score;
    }
  })

  return scoreCount;
};

更简洁的写法:

function countScores(people) {
  const scoreCount = {};
  
  people.forEach(({ name, score }) => {
    // 利用逻辑或初始化默认值为0,再累加当前分数
    scoreCount[name] = (scoreCount[name] || 0) + Number(score);
  })

  return scoreCount;
};

内容的提问来源于stack exchange,提问作者Timothy W. Times

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:40:21