1 回答

TA貢獻1784條經驗 獲得超7個贊
每次分數變化時,您都需要檢查條件。為此,將您的 if 語句放在一個單獨的函數中,并從有人得分時觸發的函數中調用它。我創建小函數是因為,在我看來,這是最佳實踐,但對于這么小的操作來說并不是必需的。
let pScore = 0;
let cScore = 0;
let user = ["Player", "Computer"];
let isGameOver = (score) => {
if (pScore === 10 || cScore === 10) {
return true;
}
return false;
}
function gameOver() {
let winner = pScore === 10 ? user[0] : user[1];
console.log(winner);
}
function theFunctionThatChangesTheScores() {
// after the code that changes the score
if ( isGameOver() ) {
// you can code in this block, but ideally.
// create another function and call it:
return gameOver();
}
return console.log("game is still on");
}
theFunctionThatChangesTheScores();
添加回答
舉報