为什么这最后一行代码是必要的?

时间:2012-10-06 04:05:42

标签: javascript

我从正在阅读的书中的示例中了解了以下所有代码。除了注释行。我想没有它,循环永远不会结束?我不明白它背后的逻辑。

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);

3 个答案:

答案 0 :(得分:2)

这是一个从99(var cans = "99")开始然后向后计数到0的循环。突出显示的行是“减去一”的行。如果它不是该行,它将继续循环并永远添加99 cans of Energy drink on the wall

顺便说一句,document.write只是错误,而var cans = "99"应该是var cans = 99。当然,这可能不是你的代码,只是说'。我的建议是:继续阅读。

答案 1 :(得分:0)

像P Strout说的那样,它是一个循环。基本上你的代码是&#34;而变量 cans 大于0然后执行此操作&#34;。如果罐头的价值永远不会改变,那么它就会失败或无限期地重复。 所以基本上你从99罐开始。对于每个罐子,它将罐子的数量减去1,直到它为0,此时环路终止。

答案 2 :(得分:0)

d。 Strout是对的......

但仅仅是一个FYI - 因为你正在学习 - 你也可以使用'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/