2012-10-06 29 views
1

我從我正在閱讀的書籍的示例中瞭解以下所有代碼。除了註釋行。我在想沒有它的循環永遠不會結束?我不明白它背後的邏輯。爲什麼最後一行代碼是必需的?

var drink = "Energy drink"; 
var lyrics = ""; 
var cans = "99"; 

while (cans > 0) { 
    lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>"; 
    lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>"; 
    lyrics = lyrics + "Take one down, pass it around, <br>"; 

    if (cans > 1) { 
     lyrics = lyrics + (cans-1) + " cans of" + drink + " on the wall <br>"; 
    } 
    else { 
     lyrics = lyrics + "No more cans of" + drink + " on the wall<br>"; 
    } 
    cans = cans - 1; // <-- This line I don't understand 
} 

document.write(lyrics); 
+0

你在編程之前的經驗嗎?這可能會幫助你http://www.tizag.com/javascriptT/javascriptwhile.php – dpp

+1

@dpp html/css我試圖學習我的方式進入html5,當然需要JavaScript。感謝所有幫助的人。我不想通過任何我正在閱讀的書籍的練習,而不是100%地理解它。 – Rufio

+0

如果你初始化罐子爲100'var cans = 100',那麼你可以擺脫那條線,然後改變條件爲'while(cans - )' – RobG

回答

2

這是開始於99(var cans = "99")循環計數然後向後爲0。加亮的行是,說「減去一個」的行。如果不是那條線,它會保持循環並永遠添加99 cans of Energy drink on the wall

BTW,document.write只是var cans = "99"var cans = 99。當然,這可能不是你的代碼,只是說'。我的建議:繼續閱讀。

+0

爲什麼需要減去一個? – Rufio

+0

剛剛編輯和更新 –

+0

倒數爲零,因爲他說 – Tom

0

像D斯特勞特說的那樣,它是一個循環。基本上你的代碼是說「而變量大於0,然後執行此操作」。如果罐頭的價值永遠不會改變,那麼它會失敗或無限重複。 所以基本上你是從99罐開始。對於每個罐子,罐子的數量減1,直到它爲0,此時環路終止。

0

D.斯特勞特是正確的...

但只是一個供參考 - 因爲你正在學習 - 你也可以做同樣的事情用「for」循環,而不是「while」循環。

像這樣:

// store the div in a variable to use later - at the bottom 
var beer_holder = document.getElementById("beer_holder"); 

// Non-alcoholic to keep it PG 
var drink = "O'Doul's"; 

var lyrics = ""; 

var cans = "99"; 

// Create a variable called 'i' and set it to the cans variable amount. 
// Check if i is greater than 0, 
// if it is, than do what is between the curly brackets, then subtract 1 from cans 
for(var i=cans; i > 0; i--){ 

    lyrics = i + " cans of " + drink + " on the wall, " + i + " cans of " + drink + 
     " take one down, pour it down the sink, " + (i - 1) + " cans of O'Doul's on the wall." 

    // take the paragraph tag and put the lyrics within it 
    // the <br/> tags make sure each lyric goes on a seperate line 
    beer_holder.innerHTML += lyrics + "<br/><br/>"; 

} 

下面是如果你想發揮與它周圍的工作示例的鏈接: http://jsfiddle.net/phillipkregg/CHyh2/

相關問題