2013-10-28 40 views
0

循環應該把每本書的價格,將其添加到總,然後把平均在頁面上的每本書,直到用戶在「N」進入爲什麼我的JavaScript循環不工作?

<script type="text/javascript"> 
var ct = 1; 
var yesORno = "Y"; 
while (yesORno = "Y"){ 
    book = prompt("What is the price of book #" + ct, 0); 
    total = parseInt(book) + total; 
    ans = total/ct; 
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>"); 
    ct = ct + 1; 
    yesORno = prompt("Would you like to continue? (Y/N)", "") 
} 
</script> 
+1

這是一個無限循環。 –

+2

'whileORno =「Y」){'should be'while(yesORno ===「Y」){'使用http://jshint.com/來查找代碼中的常見錯誤。 –

+0

(可選)您還應該檢查「y」 –

回答

8

你應該改變你而條件:

while (yesORno == "Y") 

只使用=將其分配「Y」值yesORno並返回本身,這被評價爲真,並使其永遠運行下去。

3
var ct = 1; 
var yesORno = "Y"; 
while (yesORno == "Y"){ 
    book = prompt("What is the price of book #" + ct, 0); 
    total = parseInt(book) + total; 
    ans = total/ct; 
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>"); 
    ct = ct + 1; 
    yesORno = prompt("Would you like to continue? (Y/N)", "") 
} 

看看第三行。

3

與其他人一樣,您已使用賦值運算符=而不是等號運算符==或嚴格相等運算符===

但是,您也可以使用do while循環重構您的代碼。這將消除需要有一個yesORno變量。

do { 
    //... 
} while(prompt("Would you like to continue? (Y/N)", "") === 'Y') 
+0

+1 for do..while semantic –