我正在尝试使用 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()没有记录从函数返回的数字?
桃花长相依
相关分类