我正在尝试使用 JavaScript 制作一个基本的分数跟踪器:function Player(name) { this.name = name; this.scores = [];}function addPlayer(name) { playersList.push(new Player(name)); return playersList;}function addScore(name, score) { playersList.forEach(player => { if (player.name == name) { player.scores.push(score); }; });}function getTotal(name) { playersList.forEach(player => { if (player.name == name) { let sum = 0; player.scores.forEach(score => sum += score); console.log(sum); } });}var playersList = [];addPlayer("Player1");addScore("Player1", 3);addScore("Player1", 4);console.log(getTotal("Player1"));我期待的输出是:77但相反,我得到:7undefined谁能帮我解释为什么我console.log()没有记录从函数返回的数字?
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
试试这个
function getTotal(name) {
let sum = 0;
playersList.forEach(player => {
if (player.name == name) {
player.scores.forEach(score => sum += score);
console.log(sum);
}
});
return sum
}
添加回答
举报
0/150
提交
取消