2012-10-18 84 views
2

我是Javascript新手,我試圖在循環時纏住我的頭。我瞭解他們的目的,我想我明白他們的工作方式,但我遇到了麻煩。瞭解while循環

我希望while值重複自己,直到兩個隨機數彼此匹配。目前,while循環只運行一次,如果我想重複它自己,我需要再次運行它。

如何設置此循環,以便它會自動重複if語句,直到diceRollValue === compGuess?謝謝。

diceRollValue = Math.floor(Math.random()*7); 
compGuess = Math.floor(Math.random()*7); 
whileValue = true; 

while (whileValue) { 
    if (diceRollValue === compGuess) { 
     console.log("Computer got it right!") 
     whileValue = false; 
    } 
    else { 
     console.log("Wrong. Value was "+diceRollValue); 
     whileValue = false; 
    } 
} 
+0

看起來你給自己一個複製粘貼錯誤。複製的代碼,你粘貼它,並從未改變它。但這只是問題的一半。 :) – epascarello

回答

6

這是因爲你只在這段時間之外執行隨機數生成器。如果你想要兩個新的數字,他們需要在內執行while語句。像下面這樣:

var diceRollValue = Math.floor(Math.random() * 7), 
    compGuess = Math.floor(Math.random() * 7), 
    whileValue = true; 
while (whileValue){ 
    if (diceRollValue == compGuess){ 
    console.log('Computer got it right!'); 
    whileValue = false; // exit while 
    } else { 
    console.log('Wrong. Value was ' + diceRollValue); 
    diceRollValue = Math.floor(Math.random() * 7); // Grab new number 
    //whileValue = true; // no need for this; as long as it's true 
         // we're still within the while statement 
    } 
} 

如果你想重構它,你可以使用break退出循環(而不是使用一個變量),以及:

var diceRollValue = Math.floor(Math.random() * 7), 
    compGuess = Math.floor(Math.random() * 7); 
while (true){ 
    if (diceRollValue == compGuess){ 
    // breaking now prevents the code below from executing 
    // which is why the "success" message can reside outside of the loop. 
    break; 
    } 
    compGuess = Math.floor(Math.random() * 7); 
    console.log('Wrong. Value was ' + diceRollValue); 
} 
console.log('Computer got it right!'); 
1

你有兩個問題,首先是你在if和else塊中都設置了whileValue,所以無論隨機數的值如何,循環在一次迭代後都會中斷。

其次,你在循環之前產生猜測,所以你會一遍又一遍地檢查相同的值。

因此,刪除else塊中的whileValue賦值,並將compGuess賦值移入while循環。

1

將2個隨機變量放入循環中。

whileValue = true; 

while (whileValue) { 
    diceRollValue = Math.floor(Math.random()*7); 
    compGuess = Math.floor(Math.random()*7); 
    if (diceRollValue === compGuess) { 
     console.log("Computer got it right!") 
     whileValue = false; 
    } 
    else { 
     console.log("Wrong. Value was "+diceRollValue); 
    } 
}