我寫了一個函數,該函數應該(1)生成一個隨機數,(2)判斷用戶的號碼和(3)跟蹤用戶的嘗試。JavaScript增量問題
前兩個目標已完成,但我在(3)遇到問題,跟蹤用戶嘗試。
function randNum(){
var num = Math.floor(Math.random()*(100)+1);
var usrGuess = document.forms.guess.visitor.value;
var attempt = 0;
if (usrGuess != num){
if ((usrGuess < 1) || (usrGuess > 100))
document.getElementById("wizard").innerHTML = "Fool! This number isn't even part of the set!";
else if (usrGuess > num)
document.getElementById("wizard").innerHTML = "Wrong, fool! This is greater than my number! I was thinking of " + num + "!";
else if (usrGuess < num)
document.getElementById("wizard").innerHTML = "Wrong, fool! This is less than my number! I was thinking of " + num + "!";
attempt += 1; // Here's the change.
alert(attempt); // Here's the output. It doesn't change.
}
else if (usrGuess == num){
if (attempt <= 5)
document.getElementById("wizard").innerHTML = "Right... fool. You only guessed in " + attempt + " tries.";
else if ((attempt <= 10) && (attempt > 5))
document.getElementById("wizard").innerHTML = "Right, fool. You only after " + attempt + " tries.";
else if (attempt > 10)
document.getElementById("wizard").innerHTML = "Haha, fool! You finally guessed after " + attempt + " tries.<br />Go wallow in your lost time.";
}
}
由於某些原因,即使我將「attempt」作爲外部參數,該數字只追蹤一次嘗試。
任何人都有解決方案?
嗯,我覺得很傻。我用C語言來思考,並將「嘗試」作爲randNum的一個參數。拿走這個方法使它成功(儘管我不完全確定爲什麼)。 – Pori 2012-03-08 15:17:38
感謝您的幫助。 – Pori 2012-03-08 15:18:03