带条件的开关盒

2022-01-19 00:00:00 switch-statement jquery javascript

我是否编写了带有条件的正确 switch 案例?

Am I writing the correct switch case with conditions?

var cnt = $("#div1 p").length;
alert(cnt);

switch (cnt) {
  case (cnt >= 10 && cnt <= 20):
    alert('10');
    break;
  case (cnt >= 21 && cnt <= 30):
    alert('21');
    break;
  case (cnt >= 31 && cnt <= 40):
    alert('31');
    break;
  default:
    alert('>41');
}

由于某种原因,条件匹配时没有发生警报!

For some reason, the alert does not occur when the conditions are matched!

推荐答案

您不应该在这种情况下使用 switch.这是正确的方法:

You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;

alert(cnt);

if (cnt >= 10 && cnt <= 20)
{
   alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
   alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
   alert('31');
}
else 
{
   alert('>41');
}

相关文章