当我的函数似乎返回正确答案时,为什么 console.log() 记录未定义?
Why is console.log() logging undefined when my function seems to be returning the right answer?
我正在尝试使用 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()
没有记录函数返回的数字?
试试这个
function getTotal(name) {
let sum = 0;
playersList.forEach(player => {
if (player.name == name) {
player.scores.forEach(score => sum += score);
console.log(sum);
}
});
return sum
}
我正在尝试使用 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()
没有记录函数返回的数字?
试试这个
function getTotal(name) {
let sum = 0;
playersList.forEach(player => {
if (player.name == name) {
player.scores.forEach(score => sum += score);
console.log(sum);
}
});
return sum
}