2013-10-25 103 views
0

我是新使用JavaScript,和我有一些無法理解爲什麼這個代碼不執行:遇到的麻煩「而」循環在javascript

var weight; 

wight=parseInt(prompt("Please, enter weight"); 

while(weight>0); 

{ 
    if (weight>199 && weight<300); 
{ 

    document.write("Tax will be" + weight*5); 
} 

    else 
{ 

    document.write("Tax will be" + weight*10); 
} 
} 

編輯:對不起,我在這裏寫下代碼時拼寫了一些「權重」。無論哪種方式,這不是問題。當我在谷歌瀏覽器中運行它時,它不會提示。當它提示時,它不執行'if'語句。

+0

您在一段時間後,有一個分號。去掉它。 –

+1

你也在'weight'和'wight'之間交替。 –

+1

所有的答案都是正確的,你也可以通過檢查控制檯在螢火蟲找到你自己 –

回答

3
while (wight>0); 

分號有效地使循環:當懷特大於0時,什麼都不做。這迫使一個無限循環,這就是爲什麼其他代碼不能執行。

另外,'wight'是而不是與'weight'相同。這是另一個錯誤。

此外,如果更改了該行對while (weight > 0),你仍然有一個無限循環,因爲再執行不改變「重」的代碼 - 因而,它會總是大於0(除非號在提示符處輸入小於0,在這種情況下根本不會執行)。

你想要的是:

var weight; 
weight=parseInt(prompt("Please, enter weight")); // Missing parenthesis 
// Those two lines can be combined: 
//var weight = parseInt(prompt("Please, enter weight")); 

while(weight>0) 
{ 
    if (weight>199 && weight<300)// REMOVE semicolon - has same effect - 'do nothing' 
    { 
     document.write("Tax will be" + weight*5); 
     // above string probably needs to have a space at the end: 
     // "Tax will be " - to avoid be5 (word smashed together with number) 
     // Same applies below 
    } 
    else 
    { 
     document.write("Tax will be" + weight*10); 
    } 
} 

即語法正確。您仍然需要更改while條件,或者更改該循環內的「weight」,以避免無限循環。

+0

此處還有一個缺失的緊固大括號:'weight = parseInt(prompt(「Please,enter weight」);'應該是'weight = parseInt(提示(「請輸入重量」));' – brandonscript

+0

@ r3mus剛剛發現同時編輯,謝謝 – Trojan

-1

拼寫重量:

while (wight>0); 

while (weight>0); 

document.write("Tax will be" + wight*10); 

document.write("Tax will be" + weight*10); 
-1

試試這個

var weight; 

weight=parseInt(prompt("Please, enter weight")); 

while (weight>0) 
{ 
    if (weight>199 && weight<300) 
{ 
    document.write("Tax will be" + weight*5); 
} 
    else 
{ 
    document.write("Tax will be" + weight*10); 
} 
}