![](/img/trans.png)
[英]How to call a javascript function and alter a variable in an Angular controller?
[英]How to alter the value of a variable with a function?
我正在構建“Number Guesser Game”的代碼。 每場比賽結束后如何更改分數?
這是我第一次在線課程的無輔助作業。 我對使用什么來達到某些結果沒有基本的了解,所以我提前為noob問題道歉。
我被困在任務5號:
創建updateScore()函數。 此功能將用於在每輪后正確增加獲勝者的分數。
這個功能:
有一個參數。 此參數將是表示獲勝者的字符串值。 將得分變量(humanScore或computerScore)增加1,具體取決於傳遞給updateScore的獲勝者。 傳入的字符串將是“人”或“計算機”。 不需要返回任何值。
首先:為什么我需要創建一個功能來改變記分牌? 在“compareGuesses”函數中設置勝利后,我不能只編寫代碼來改變它嗎?
這是我到目前為止:
//在下面寫下你的代碼:
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
const generateTarget = Math.floor(Math.random() * 9)
const compareGuesses = (humanGuess, computerGuess,targetGuess) => {
if (Math.abs (humanGuess-targetGuess() )<Math.abs( computerGuess-targetGuess() )){ return true;
} else if (Math.abs (humanGuess-targetGuess() )> Math.abs( computerGuess-targetGuess() )){
return false;
}
}
const updateScore = (winner) => {
if (compareGuesses= true) {
}
首先:為什么我需要創建一個功能來改變記分牌? 在“compareGuesses”函數中設置勝利后,我不能只編寫代碼來改變它嗎?
是的,您可以這樣做,但為了幫助實現代碼可維護性(以及許多其他事情),將較大的應用程序/問題的單獨塊或模塊拆分為較小的函數通常是個好主意。 這種想法被稱為分解 。 因此,通過創建諸如updateScore
和compareGuesses
類的單獨函數,您可以將更大的問題分解為更小的更易維護的問題。
現在為您的updateScore
功能。 你的描述說它會接受一個字符串,無論是"human"
還是"computer"
。 您需要檢查獲勝者是"human"
還是"computer"
並更新相關的分數變量。 以下是如何實現此目的的示例:
const updateScore = (winner) => {
if(winner === 'human') {
humanScore += 1; // humanScore++; will also work here
} else if(winner === 'computer') {
computerScore += 1; // computerScore++; will also work here
}
}
因此,如果您想要提高玩家得分,如果他正確地猜測數字並且如果猜測不正確則增加計算機得分,則該功能可能如下所示:
function score(humanScore, computerScore) {
if (humanGuess - computerGuess === 0) {
humanScore += 1
}
else {
computerScore += 1
}
alert(humanScore)
alert(computerScore)
}
當然,你需要調用這樣的函數:
score(humanScore, computerScore)
嘗試這樣的事情:
class Game {
humanScore = 0;
computerScore = 0;
currentRoundNumber = 1;
target = 0;
generateTarget() {
this.target = Math.floor(Math.random() * 9)
}
nextRound(humanGuess, computerGuess) {
this.currentRoundNumber++;
if (Math.abs(humanGuess-this.target) < Math.abs(computerGuess-this.target))
this.humanScore++;
else if (Math.abs(humanGuess-this.target) > Math.abs(computerGuess-this.target))
this.computerScore++;
}
}
const game = new Game();
game.generateTarget();
game.nextRound(333, 42);
PS:StackOverflow不在這里做你的功課。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.