javascript 中的“while"循环有问题 [英] Having trouble with 'while' loop in javascript

查看:16
本文介绍了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.

此外,如果您将该行更改为 while (weight > 0),您仍然会遇到无限循环,因为随后执行的代码不会改变权重" - 因此,它将总是大于 0(除非在提示中输入了小于 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 条件,或更改该循环内的权重",以避免无限循环.

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天全站免登陆