我从我正在阅读的一本书上的一个示例中理解了以下所有代码。除了注释行。我在想,没有它,循环就永远不会结束?不过,我不明白它背后的逻辑。
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);发布于 2012-10-06 12:07:11
这是一个从99 (var cans = "99")开始的循环,然后向后计数到0。突出显示的行是“减一”的行。如果不是这一行,它将永远循环并添加99 cans of Energy drink on the wall。
顺便说一句,document.write是不好的,var cans = "99"应该是var cans = 99。当然,这可能不是你的代码,只是说说而已。我的建议是:继续读下去。
发布于 2012-10-06 12:09:12
就像D·斯特劳特说的,这是一个循环。基本上,你的代码是说“当变量cans大于0时,执行这个操作”。如果cans的值永远不会改变,那么它将失败或无限重复。所以基本上你是从99罐开始的。对于每个罐头,它将罐头数量减去1,直到其为0,此时循环终止。
发布于 2012-10-06 12:55:17
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/
https://stackoverflow.com/questions/12756637
复制相似问题