JavaScript列表元素求和:2007赛季球队积分函数报错排查
你的代码问题分析与修正方案
首先,咱们先拆解你代码里的几个核心问题,这些问题直接导致了函数无法正常运行:
主要问题点
- 变量名混乱&未初始化:你声明了
var results;但没赋值(此时它是undefined),后面却用了result.forEach(注意少了个s),不仅变量名拼写错误,而且undefined根本没有forEach方法,直接会抛出报错。 - 大小写敏感问题:JavaScript是严格区分大小写的,原数据里的属性是
points、season,但你代码里写了Points、Season,这样会取不到对应的值,最终得到NaN或者undefined。 - 遍历逻辑完全混乱:你的嵌套遍历层级搞反了,而且错误地把遍历出来的元素当成了索引(比如
result[s].forEach),这完全不符合数组遍历的逻辑。另外Season.map(Game => Points)里的Points是未定义的变量,正确应该是取Game.points。 - 错误的属性赋值逻辑:你试图给
results[s].Points赋值,但results本身都没初始化,这种写法根本不成立。
修正后的实现方案
根据你的需求(对2007赛季的所有积分求和),这里分两种场景给出实现:
场景1:计算所有队伍2007赛季的总积分
const teamRecords = [ { team: 'A', results: [ { season: '2007', game: 'G1', points: 3 }, { season: '2007', game: 'g2', points: 3 }, { season: '2008', game: 'G1', points: 5 } // 非2007赛季的会被过滤 ] }, { team: 'B', results: [ { season: '2007', game: 'G1', points: 4 }, { season: '2007', game: 'g2', points: 2 } ] } ]; // 计算所有队伍2007赛季总积分 const total2007Points = teamRecords.reduce((total, team) => { // 筛选当前队伍2007赛季的记录,然后求和 const team2007Points = team.results .filter(game => game.season === '2007') .reduce((sum, game) => sum + game.points, 0); return total + team2007Points; }, 0); console.log(total2007Points); // 输出:3+3+4+2 = 12
场景2:计算每个队伍2007赛季的积分总和,并保留队伍信息
const team2007Records = teamRecords.map(team => { const totalPoints = team.results .filter(game => game.season === '2007') .reduce((sum, game) => sum + game.points, 0); return { team: team.team, 2007TotalPoints: totalPoints }; }); console.log(team2007Records); // 输出: // [ { team: 'A', 2007TotalPoints: 6 }, { team: 'B', 2007TotalPoints: 6 } ]
关键逻辑说明
- 先用
filter筛选出season等于'2007'的比赛记录,排除其他赛季的数据。 - 再用
reduce对筛选后的points进行累加求和,第二个参数0是累加的初始值,避免空数组时返回undefined。 - 外层的
reduce(场景1)用来累加所有队伍的积分,map(场景2)用来为每个队伍生成对应的积分统计结果。
内容的提问来源于stack exchange,提问作者Peter Nick
相关产品推荐
相关产品推荐

