2013-10-25 104 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); 
} 
}