JavaScript switch语句仅触发第一种情况

时间:2019-01-20 20:37:47

标签: javascript switch-statement

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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

在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 >= 33 <= 66:您 需要添加“和”运算符case >= 33 **&&** <= 66:
  • 我将a[2]更改为a,所以它不会出错,因为它没有命名 正确

总的来说,像Morgan Wilde所述的if和else语句更容易使用。