繁体   English   中英

无法在JavaScript中使用“ while”循环

[英]Having trouble with 'while' loop in 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”语句。

while (wight>0);

分号有效地导致了该循环:当wight大于0时,不执行任何操作。 这将导致无限循环,这就是为什么其余代码无法执行的原因。

此外,“怀特”是一样的“权重”。 这是另一个错误。

此外,如果将该行更改为while (weight > 0) ,则仍然会有一个无限循环,因为随后执行的代码不会更改'weight'-因此,它将始终大于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条件,或更改该循环内的“权重”,以避免无限循环。

重量拼写:

while (wight>0);

while (weight>0);

也在

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

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

尝试这个

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);
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM