【问题标题】:javascript ignore my IF Statements whan useing while Statementsjavascript 在使用 while 语句时忽略我的 IF 语句
【发布时间】:2019-04-23 16:46:57
【问题描述】:

所以我有一个javascript练习 现在是一些 PHP,但那是很久以前的事了,我开始回到代码上来。 我参加了一门网络开发课程,我需要打印 5 和 50 之间可被 5 和 3 整除的所有数字。 所以它没有那么多工作,并且忽略了我的 if 和 else 声明。 我想了解它为什么会发生。 tnx 适合所有人

console.log("PRINT ALL NUMBERS DIVISIBLE BY 5 AND 3 BETWEEN 5 AND 50");
var num = 0 ;
if(num = 0){
  num++;
  console.log(num + " first if");
}
else if (!(num % 3 === 0 && num % 5 === 0)){
  num ++;
console.log(num + " second if");
}
else {
  while(num <= 50){
  console.log(num);
  num++;
}
}

【问题讨论】:

  • if(num = 0) - = 表示 assignment。对于相等性检查,请使用 =====
  • 另外:您为被 3 和 5 整除所做的任何检查都需要在循环内。此外:使用(num % 3 === 0 &amp;&amp; num % 5 === 0),您正在检查一个数字是否可以被 15 整除。我猜这不是练习的重点。
  • tnx 帮了大忙

标签: javascript if-statement while-loop


【解决方案1】:

您的循环配置错误,请将您的 if 语句放在整个循环中...

var num = 0;
while(num <= 50) {
    if (num == 0) {
        console.log(num + " is zero");
    } else if (num % 3 === 0 && num % 5 === 0) {
        console.log(num + " divisible by 3 and 5");
    } else {
        console.log(num);
    }
    num++;
}

【讨论】:

  • 我会将第一个 if 放在循环之外,因为它只运行一个 num,但你帮了我很多。 tnx
猜你喜欢
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2018-03-26
相关资源
最近更新 更多