2015-11-06 49 views
0

我正在做一個在線課程的練習來學習Javascript。這只是第一個,我有問題,所以在進展之前,我真的很想理解它。獲取一個while循環的條件以便一次打印出錯

問題是這樣的:

complete the while loop in the editor so it will print out "I'm learning while loops!". Do this by adding the condition between the parentheses—don't change line 5, or you could get an infinite loop!

的代碼是:

var understand = true; 

while(){ 
    console.log("I'm learning while loops!"); 
    understand = false; 
} 

我嘗試添加這條件:

while(understand === 0){

但我正在逐漸這個錯誤

糟糕,請再試一次。它看起來像你沒有打印到控制檯的字符串。檢查你的循環語法!

我在做什麼錯在我的情況?有人可以詳細說明,所以我可以學習這個關鍵的基礎。謝謝!

這個練習之前,例如:

var coinFace = Math.floor(Math.random() * 2); 

while(coinFace === 0){ 
    console.log("Heads! Flipping again..."); 
    var coinFace = Math.floor(Math.random() * 2); 
} 
console.log("Tails! Done flipping."); 

編輯---更新:

You may have noticed that when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance, 

var bool = true; 
while(bool){ 
    //Do something 
} 
is the same thing as 

var bool = true; 
while(bool === true){ 
    //Do something 
} 
but the first one is faster to type. Get in the habit of typing exactly as much as you need to, and no more! 

If you happen to be using numbers, as we did earlier, you could even do: 
+3

'while(understand){'。但是,你需要閱讀關於while循環的部分,因爲你還沒有真正理解它。 – dfsq

+0

我可以建議,如果這是在線課程中的_first_練習,並且您在完成練習時遇到問題,則該課程可能不是最高質量的,因爲您不需要猜測答案... –

+0

It是一個codeacademy課程。他們展示了一段時間的陳述,然後在後面給出了這個問題。它看起來不像他們給的例子。 – Becky

回答

2

這是while(understand === true)

由於環路將觸發第一次,因爲understand已經設置爲真。然後,當它觸發時,它會將understand設置爲false - 所以下次嘗試觸發循環時,條件將失敗並且不會繼續。這樣,您就可以執行一次循環,因此只能打印一次。

+0

感謝您的闡述。因爲我已經把'理解'設置爲真,所以我'同時(理解)'。這很有道理。 – Becky

+0

@Becky重要的是要注意,嚴格的比較總是會更快執行,並且不會出錯。如果你這樣做(理解),理解可以設置爲一個字符串或數組,並且一段時間將繼續激發。如果你這樣做===真,那麼你只是說如果它完全等於真,那麼如果它在一段時間內都會改變就會停止。只有良好的編程習慣,當你進入事物時,試着讓你的條件總是有三個等號或者比較大/小。 –

+0

那麼,在全球範圍內創建變量沒有意義,只是保持它在本地的內部?對不起,如果術語關閉。還是新的。 – Becky

0

如果你有代碼看起來像這樣

while(true){ 
    console.log("I'm learning while loops!"); 
    understand = false; 
} 

,你會得到一個無限循環!循環將繼續進行,因爲條件將始終爲真。現在,如果只有某種方式,如條件中的變量,才能使條件爲false。