在javascript中使用'while'循环时遇到问题 [英] Having trouble with 'while' loop in javascript

查看:121
本文介绍了在javascript中使用'while'循环时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,我在理解为什么这段代码无法执行时遇到了一些麻烦:

I'm new with javascript, and I'm having some trouble understanding why this code doesn't execute:

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

I'm sorry, I mispelled some 'weights' while writing down the code here. Either way, that's not the problem. When I run this in google chrome, it just doesn't prompt. And when it prompted, it doesn't execute the 'if' statement.

推荐答案

while (wight>0);



<分号有效地产生了循环:当wight大于0时,什么都不做。这会强制一个无限循环,这就是你的代码的其余部分不执行的原因。

The semicolon effectively makes that loop: while wight is greater than 0, do nothing. This forces an infinite loop, which is why the rest of your code doesn't execute.

此外,'wight' 与'weight'相同。这是另一个错误。

Also, 'wight' is not the same as 'weight'. This is another error.

此外,如果您将该行更改为而(重量> 0),你仍然会有一个无限循环,因为然后执行的代码不会改变'权重' - 因此,总是大于0(除非a在提示符下输入小于0的数字,在这种情况下它根本不会执行。)

Furthermore, if you change that line to while (weight > 0), you will still have an infinite loop, because the code that then executes does not alter 'weight' - thus, it will always be greater than 0 (unless a number less than 0 was entered at the prompt, in which case it won't execute at all).

你想要的是:

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',以避免无限循环。

That is syntactically correct. You still need to either change the while condition, or alter 'weight' within that loop, to avoid an infinite loop.

这篇关于在javascript中使用'while'循环时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆