【问题标题】:Having trouble with 'while' loop in javascriptjavascript中的'while'循环有问题
【发布时间】:2013-10-25 04:55:27
【问题描述】:

我是 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'语句。

【问题讨论】:

  • 你有一个分号。删除它。
  • 你也在weightwight之间交替。
  • 所有答案都是正确的,您也可以通过在 firebug 上查看控制台找到自己
  • 分号意味着什么。它们不仅仅是你在代码中散布以使其看起来漂亮的装饰元素。
  • 有没有解决这个问题的答案?

标签: javascript loops while-loop


【解决方案1】:
while (wight>0);

分号有效地构成了循环:当 wight 大于 0 时,什么也不做。这会强制执行无限循环,这就是您的其余代码不执行的原因。

另外,“wight”与“weight”相同。这是另一个错误。

此外,如果您将该行更改为 while (weight &gt; 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=parseInt(prompt("Please, enter weight"); 应该是 weight=parseInt(prompt("Please, enter weight"));
【解决方案2】:

重量的拼写:

while (wight>0);

while (weight>0);

也在

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

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

【讨论】:

    【解决方案3】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2011-06-19
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      相关资源
      最近更新 更多