猿问

当我的函数似乎返回正确答案时,为什么 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()没有记录从函数返回的数字?


小唯快跑啊
浏览 90回答 1
1回答

桃花长相依

试试这个function getTotal(name) {  let sum = 0;  playersList.forEach(player => {    if (player.name == name) {                player.scores.forEach(score => sum += score);        console.log(sum);    }   });  return sum}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答