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

3 回答 3

2

这是一个从 99 ( var cans = "99") 开始的循环,然后倒数到 0。突出显示的行是表示“减一”的行。如果不是那条线,它会一直循环并99 cans of Energy drink on the wall永远添加。

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

于 2012-10-06T04:07:11.423 回答
0

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

于 2012-10-06T04:09:12.067 回答
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/

​</p>

于 2012-10-06T04:55:16.703 回答