【问题标题】:Switch Statements and ModuloSwitch 语句和取模
【发布时间】:2020-06-19 18:02:59
【问题描述】:

嗨,我有点困惑,为什么我没有在这个函数中记录任何内容。如果我通过函数传递 10,不应该记录“case2”吗?我认为这与我编写模线的方式有关...

 function helloWorld(num) {
        switch (num){
                case num % 3 === 0:
                    console.log('case1');
                    break

                case num % 5 === 0:
                     console.log('case2');
                     break

                case num % 3 === 0 && num % 5 ===0:
                     console.log('case3');
                     break
            }
        }

 helloWorld(10);

【问题讨论】:

  • 不要滥用switch 声明,如果您想要的话,只需使用if/else 级联即可。仅将 switch 语句与 cases 中的常量一起使用。
  • "为什么我没有记录任何内容" - 因为您的情况下的布尔表达式永远不会匹配您正在使用的 num switch

标签: javascript switch-statement modulo


【解决方案1】:

case 语句旨在用于将值与switch 语句中指定的值进行比较。

您正在每个 case 中添加一个布尔条件,从而强制执行意外行为。你所做的在形式上是正确的,但在语义上是不正确的。

这是正确的代码:

 function helloWorld(num) {
   if((num % 3) === 0)
     console.log('case1');

   else if((num % 5) === 0)
     console.log('case2');

   else if((num % 3) === 0 && (num % 5) === 0)
     console.log('case3');
 }

helloWorld(10);

有关switch声明的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2021-04-26
    相关资源
    最近更新 更多