当我的函数似乎返回正确答案时,为什么console.log()记录未定义?

时间:2020-04-17 02:10:37

标签: javascript console.log

我正在尝试使用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"));

我期望的输出是:

7
7

但是我得到了:

7
undefined

有人可以帮我解决为什么我的console.log()不记录该函数返回的数字吗?

1 个答案:

答案 0 :(得分:0)

尝试这个

function getTotal(name) {
  let sum = 0;
  playersList.forEach(player => {
    if (player.name == name) {        
        player.scores.forEach(score => sum += score);
        console.log(sum);
    } 
  });
  return sum
}