我从正在阅读的书中的示例中了解了以下所有代码。除了注释行。我想没有它,循环永远不会结束?我不明白它背后的逻辑。
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 :(得分:2)
这是一个从99(var cans = "99"
)开始然后向后计数到0的循环。突出显示的行是“减去一”的行。如果它不是该行,它将继续循环并永远添加99 cans of Energy drink on the wall
。
顺便说一句,document.write
只是错误,而var cans = "99"
应该是var cans = 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/