2012-03-08 68 views
-1

我寫了一個函數,該函數應該(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」作爲外部參數,該數字只追蹤一次嘗試。

任何人都有解決方案?

回答

4

您聲明「attempt」爲局部變量。每次調用函數時都會重新初始化。

你也彌補每次通話的功能,這似乎有點意思:-)

聲明函數外部變量,看看它是如何進入一個新的隨機數。 (然而,在裏面保留「usrGuess」;只是移動「num」和「attempt」)。

0

你有var attempt = 0範圍內的功能。每次調用此函數時,它都會將attempt設置爲0.聲明attempt函數以外的內容,並查看它是如何工作的。

而且,我更喜歡下面的符號爲增量:attempt++;

+0

嗯,我覺得很傻。我用C語言來思考,並將「嘗試」作爲randNum的一個參數。拿走這個方法使它成功(儘管我不完全確定爲什麼)。 – Pori 2012-03-08 15:17:38

+0

感謝您的幫助。 – Pori 2012-03-08 15:18:03