【问题标题】:Operators in javascript switch case [duplicate]javascript switch case中的运算符[重复]
【发布时间】:2014-07-31 13:06:31
【问题描述】:

为什么会返回默认大小写:

var score=parseInt(3);
switch(score))
{
 case(score<1):
  alert('DUFF');
  break;
 case(score<5):
  alert('AWESOME');
  break;
 default:
  alert('NOPE');
  break;
}

我已经研究过了,但没有找到任何解决方案。

【问题讨论】:

  • 为了简洁起见,我修剪了代码。也许您不应该为迭代过程这样做。我实际上有几十个潜在的分数要测试(不仅仅是 1 和 5)。这篇文章link 上接受的答案建议布尔运算符是可能的,所以这变成了一个“我的代码为什么不起作用”的问题,我并不认为它是重复的。我现在开悟了。

标签: javascript switch-statement


【解决方案1】:

因为具有3 整数值的score 永远不会变成布尔值truefalse,因为(score &lt; 1)false(score &lt; 5)true

switch 语句检查传递的变量(或值)是否等于其中一种情况,即:

switch (score) {
    case 1:
        // score is 1
        break;
    case 3:
        // score is 3
        break;
    case true:
        // score is true
        break;
    default:
        // neither of above
}

您尝试使用switch 语句实现的目标可以按如下方式完成:

switch (true) {
    case (score < 1):
        alert('DUFF');
        break;
    case (score < 5):
        alert('AWESOME');
        break;
    default:
        alert('NOPE');
}

【讨论】:

    【解决方案2】:

    这段代码变成:

    var score=3; // No need for parse here
    switch(score)
    {
     case(false): /*score<1 */
      alert('DUFF');
      break;
     case(true): /* score<5 */
      alert('AWESOME');
      break;
     default:
      alert('NOPE');
      break;
    }
    

    你需要:

    var score= 3;
    
    if (score<1) {
      alert('DUFF');
    } else if (score<5) {
      alert('AWESOME');
    } else {
      alert('NOPE');
    }
    

    【讨论】:

      【解决方案3】:

      这是javascript: using a condition in switch case 的副本


      话虽如此,最好只使用 if 语句。您可以在 case 语句中使用条件(不仅仅是值),只需删除括号即可(请参阅上面的链接 SO 帖子)。

      当您不进行模式匹配时,ifs 很好:

      var score = parseInt(3);
      if (score < 1) {
          alert('DUFF');
      } else if (score < 5) {
          alert('AWESOME');
      } else {
          alert('NOPE');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 2017-10-02
        • 2017-04-05
        • 1970-01-01
        • 2011-07-28
        相关资源
        最近更新 更多