【问题标题】:Javascript switch statement only triggering first caseJavascript switch 语句仅触发第一种情况
【发布时间】:2019-01-20 20:37:46
【问题描述】:

a[2] 是一个从 1 到 100 的随机整数变量。当它小于 33 时,它变为红色,但当它高于 33 时,它保持黑色。有人知道为什么它会忽略最后两个案例吗?

<script type="text/javascript">
  switch (a[2]) {
    case < 33:
      document.getElementByID('speechstat').style.color = "red";
      break;

    case >= 33 && <= 66:
      document.getElementByID('speechstat').style.color = "blue";
      break;

    case > 66:
      document.getElementByID('speechstat').style.color = "green";
      break;
  }
</script>

【问题讨论】:

标签: javascript switch-statement


【解决方案1】:

在 JavaScript 中,switch 语句的外观与您发布的不同。例如,这里有一些documentation on switch statements on MDN

如果您想检查范围,您应该使用常规的if/else 语句进行检查。

<script type="text/javascript">
    var color;

    // Check the possible value ranges.
    if (a[2] < 33) { color = 'red'; }
    else if (a[2] >= 33 && a[2] <= 66) { color = 'blue'; }
    else if (a[2] > 66) { color = 'green'; }

    document.getElementByID('speechstat').style.color = color;
</script>

【讨论】:

    【解决方案2】:

    在 Javascript 中,您无法将变量与 switch 进行比较,但您可以间接地这样做,因为这篇文章的答案显示:switch statement to compare values greater or less than a number

    通过一些编辑并添加一些 html 来检查一切是否正常,这就是您在您的情况下将如何执行此操作:

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="speechstat1"></p>
    <p id="speechstat2"></p>
    <p id="speechstat3"></p>
    
    <script type="text/javascript">
        var a = 34; //You can set this to whatever you want or a user's input
        switch (true) {
    
            case (a<33):
                document.getElementById("speechstat1").innerHTML = "red works";
                break;
    
            case a>= 33 && a<= 66:
                document.getElementById('speechstat2').innerHTML = "blue works";
                break;
    
            case a> 66:
                document.getElementById("speechstat3").innerHTML = "green works";
                break;          
        }
    
      </script>
      </body>
    </html>
    
    • 我输入.innerHTML 只是为了证明它有效,在你的情况下你可以替换那些 符合您想要的任何事情。
    • 我把Switch改成了switch
    • 我将.getElementByID 更改为.getElementById 拼写很重要!
    • 如果你在两个条件下测试一个变量:case &gt;= 33 &lt;= 66:你 需要添加“和”运算符case &gt;= 33 **&amp;&amp;** &lt;= 66:
    • 我将a[2] 更改为a,所以它不会出错,因为它没有命名 正确

    总的来说,像 Morgan Wilde 提到的那样,使用 if 和 else 语句更容易。

    【讨论】:

    • @user10421273 如果此答案对您有所帮助,请考虑对其进行投票。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2011-11-21
    相关资源
    最近更新 更多