在此處輸入影像描述這是我的輸出影像:
function bottles_of_beer(){
var i=99;
while(i>=0){
if(i==1){
console.log(i " bottles of beer on the wall, " i " bottles of beer.\nTake one down and pass it around, No more bottles of beer on the wall.");
}
else if(i==0){
console.log("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.");
}
else{
console.log(i " bottles of beer on the wall, " i " bottles of beer.\nTake one down and pass it around, " i-1 " bottles of beer on the wall.")
}
i--;
}
}
我期待在控制臺中列印 100 次輸出。但它只是列印 i=1 和 i=0 的輸出,而對于 i : 99 to 2 它只是列印一個輸出。為什么會發生這種情況,有人可以解釋一下嗎?以及如何在控制臺中顯示/列印輸出 100 次?
這是我呼叫“bottles_of_beer()”時得到的輸出:
墻上有 98 瓶 NaN 啤酒。
1瓶啤酒在墻上,1瓶啤酒。拿下來傳給別人,墻上不再有啤酒瓶。
墻上不再有啤酒瓶,不再有啤酒瓶。去商店再買一些,墻上有 99 瓶啤酒。
uj5u.com熱心網友回復:
在您的最后一個控制臺日志中:
console.log(
i
" bottles of beer on the wall, "
i
" bottles of beer.\nTake one down and pass it around, "
i -
1
" bottles of beer on the wall."
);
之前的所有-1內容都可以作為字串,但是當您有some_string - 1JS 嘗試將字串轉換為數字然后減去 1 時。這就是您得到 NaN 的原因。
i - 1要解決它,只需將您的最后一個控制臺日志包裝在一些括號中
console.log(
i
" bottles of beer on the wall, "
i
" bottles of beer.\nTake one down and pass it around, "
(i - 1)
" bottles of beer on the wall."
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496362.html
標籤:javascript 循环
上一篇:如何在DOM中取消注釋行內腳本
