【问题标题】:Else If statement with numbers [duplicate]带有数字的Else If语句[重复]
【发布时间】:2021-07-19 10:02:01
【问题描述】:

我的代码似乎没有工作,我不知道为什么,我知道 else if 语句,所以也许我这样做完全错误。我需要用户输入一个数字,然后根据他们输入的数字打印出一条语句。

请查看下面的代码,用户输入数字并按回车后,我收到的错误消息是“未定义”。

let waterPay = prompt("Please enter the amount of water you use to get a price you need to pay, thank you!");

if (waterPay > 6000) {
  console.log("The number is below 6000");
} else if (waterPay(6000 <= 10500)) {
  console.log("The number is between 6000 and 10500");
} else if (waterPay(10.5 <= 35000)) {
  console.log("The number is between 10500 and 35000");
} else(waterPay( <= 35000)) {
  console.log("The number is above 35000");
}

【问题讨论】:

  • 你应该改用(waterPay &gt; 6000 &amp;&amp; waterPay &lt;= 10500)
  • 我建议浏览一些 JS 教程或四处寻找 if 语句表达式的样子——其中只有一个是正确的。
  • huuh?if (waterPay &gt; 6000) {console.log("The number is below 6000");}这不应该是“”数字超过6000“”
  • "在用户输入数字并按回车后,我得到的是“未定义”。" 如果您使用上面的代码,我非常怀疑您是否得到提示什么。它包含几个语法错误。

标签: javascript if-statement


【解决方案1】:

快速浏览一下,if-else-if 的结构似乎是正确的。不过,您的比较似乎存在问题。例如 waterPay (6000 6000 && waterPay

还要确保所有分支都可以访问,即条件不重叠

【讨论】:

    【解决方案2】:

    查看if...else page on mdn 以查看预期的语法。

    let waterPay = prompt("Please enter the amount of water you use to get a price you need to pay, thank you!");
    
    if (waterPay < 6000) {
      console.log("The number is below 6000");
    } else if (waterPay <= 10500) {
      console.log("The number is between 6000 and 10500");
    } else if (waterPay <= 35000) {
      console.log("The number is between 10501 and 35000");
    } else {
      console.log("The number is above 35001");
    }

    【讨论】:

    • (waterPay &lt;= 10500) 应该是(waterPay &gt; 6000 &amp;&amp; waterPay &lt;= 10500)
    • @Anonymous If waterPay &lt; 6000,if-block 将被输入,else if (waterPay &lt;= 10500) 将永远不会被执行。因此waterPay &gt; 6000(或&gt;=)不是必需的。
    • @Ivar 哦该死的我怎么可能没有意识到这一点,我觉得我太笨了 rn lmao
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多