【问题标题】:Switch method : why is num giving me 'num is unknown'? [duplicate]切换方法:为什么 num 给我“num 未知”? [复制]
【发布时间】:2020-10-20 14:21:02
【问题描述】:

function testNum(a) {
  switch (a) {
    case a > 0:
      alert("positif num");
      break;
    case a < 0:
      alert("num is negative");
      break;
    default:
      alert("num is unknown");
  }
}

testNum(4);

所以我试图用 Swtich 方法做这个简单的 if 语句,而 smh 根本没有按我想要的方式工作,为什么它不给我 'num 是肯定的',???

【问题讨论】:

  • 对 case 表达式求值,然后将 a 与结果值进行比较。 4 不等于true。
  • 您应该使用if 语句而不是switch 语句
  • 是的,我知道我可以使用 if 语句,我想知道如何使用 switch,谢谢各位

标签: javascript switch-statement


【解决方案1】:

在 javascript 中切换计算表达式而不是数字...常见的解决方法是使用

 switch(true){

 }

见下文:

function testNum(a) {
  switch (true) {
    case a > 0:
      alert("positif num");
      break;
    case a < 0:
      alert("num is negative");
      break;
    default:
      alert("num is unknown");
  }
}

testNum(4);

【讨论】:

    【解决方案2】:

    如果使用 If 或这种方式,则不能使用条件

    function testNum(a) {
      switch (true) {
        case a > 0:
          alert("positif num");
          break;
        case a < 0:
          alert("num is negative");
          break;
        default:
          alert("num is unknown");
      }
    }
    
    testNum(4)
    

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多