带条件的开关盒 [英] Switch case with conditions

查看:28
本文介绍了带条件的开关盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否编写了带有条件的正确 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');
}

这篇关于带条件的开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆