如何在使用 JavaScript 的 switch case 语句中使用范围?

2023-09-07前端开发问题
50

本文介绍了如何在使用 JavaScript 的 switch case 语句中使用范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何在使用 JavaScript 的 switch case 语句中使用范围?因此,我不想为每一种可能性编写代码,而是将它们按范围分组,例如:

How can I use ranges in a switch case statement using JavaScript? So, instead of writing code for each and every single possibility, I'd like to group them in ranges, For example:

switch(myInterval){
   case 0-2:
      //doStuffWithFirstRange();
      break;

   case 3-6:
      //doStuffWithSecondRange();
      break;

   case 6-7:
      //doStuffWithThirdRange();
      break;

   default:
      //doStuffWithAllOthers();
}

推荐答案

你至少有四个选择:

如 LightStyle 所示,您可以明确列出每个案例:

As shown by LightStyle, you can list each case explicitly:

switch(myInterval){

    case 0:
    case 1:
    case 2:
        doStuffWithFirstRange();
        break;

    case 3:
    case 4:
    case 5:
        doStuffWithSecondRange();
        break;

    case 6:
    case 7:
        doStuffWithThirdRange();
        break;

    default:
        doStuffWithAllOthers();
}

2.使用 if/else if/else

如果范围很大,那会变得笨拙,所以你会想要做范围.请注意,使用 if...else if...else if,如果较早的匹配,则不会到达后面的,因此您每次只需指定上限.为了清楚起见,我将在 /*...*/ 中包含下限,但通常您会保留它以避免引入维护问题(如果您包含两个边界,则很容易更改一个而忘记改变另一个):

2. Use if / else if / else

If the ranges are large, that gets unwieldy, so you'd want to do ranges. Note that with if...else if...else if, you don't get to the later ones if an earlier one matches, so you only have to specify the upper bound each time. I'll include the lower bound in /*...*/ for clarity, but normally you would leave it off to avoid introducing a maintenance issue (if you include both boundaries, it's easy to change one and forget to change the other):

if (myInterval < 0) {
    // I'm guessing this is an error
}
else if (/* myInterval >= 0 && */ myInterval <= 2){
    doStuffWithFirstRange();
}
else if (/* myInterval >= 3 && */ myInterval <= 5) {
    doStuffWithSecondRange();
}
else if (/* myInterval >= 6 && */ myInterval <= 7) {
    doStuffWithThirdRange();
}
else {
    doStuffWithAllOthers();
}

3.将 case 与表达式一起使用:

JavaScript 的不寻常之处在于您可以在 case 语句中使用表达式,因此我们可以将上面的 if...else if...else if 序列写为switch 语句:

3. Use case with expressions:

JavaScript is unusual in that you can use expressions in the case statement, so we can write the if...else if...else if sequence above as a switch statement:

switch (true){

    case myInterval < 0:
        // I'm guessing this is an error
        break;    
    case /* myInterval >= 0 && */ myInterval <= 2:
        doStuffWithFirstRange();
        break;

    case /* myInterval >= 3 && */ myInterval <= 5:
        doStuffWithSecondRange();
        break;

    case /* myInterval >= 6 && */ myInterval <= 7:
        doStuffWithThirdRange();
        break;

    default:
        doStuffWithAllOthers();
}

我不提倡这样做,但它 JavaScript 中的一个选项,而且有时它很有用.case 语句会根据您在 switch 中给出的值按顺序进行检查.(同样,在许多情况下可以省略下限,因为它们会更早匹配.) 即使 case 是按源代码顺序处理的,default 可以出现在任何地方(不仅仅是在末尾),并且仅在没有匹配的 case 或匹配的 case 并通过默认值时才被处理(没有break;你很少想这样做,但它确实发生了).

I'm not advocating that, but it is an option in JavaScript, and there are times it's useful. The case statements are checked in order against the value you give in the switch. (And again, lower bounds could be omitted in many cases because they would have matched earlier.) Even though the cases are processed in source-code order, the default can appear anywhere (not just at the end) and is only processed if either no cases matched or a case matched and fell through to the default (didn't have a break; it's rare you want to do that, but it happens).

如果您的函数都采用相同的参数(可能没有参数,或者只是相同的参数),另一种方法是调度映射:

If your functions all take the same arguments (and that could be no arguments, or just the same ones), another approach is a dispatch map:

在一些设置代码中:

var dispatcher = {
    0: doStuffWithFirstRange,
    1: doStuffWithFirstRange,
    2: doStuffWithFirstRange,

    3: doStuffWithSecondRange,
    4: doStuffWithSecondRange,
    5: doStuffWithSecondRange,

    6: doStuffWithThirdRange,
    7: doStuffWithThirdRange
};

然后代替开关:

(dispatcher[myInterval] || doStuffWithAllOthers)();

通过在 dispatcher 映射上查找要调用的函数来工作,如果该特定 myInterval 值没有条目,则默认为 doStuffWithAllOthers使用 功能强大的 || 运算符,然后调用它.

That works by looking up the function to call on the dispatcher map, defaulting to doStuffWithAllOthers if there's no entry for that specific myInterval value using the curiously-powerful || operator, and then calling it.

您可以将其分成两行以使其更清晰:

You can break that into two lines to make it a bit clearer:

var f = dispatcher[myInterval] || doStuffWithAllOthers;
f();

我使用了一个对象以获得最大的灵活性.您可以在您的具体示例中像这样定义 dispatcher:

I've used an object for maximum flexibility. You could define dispatcher like this with your specific example:

var dispatcher = [
    /* 0-2 */
    doStuffWithFirstRange,
    doStuffWithFirstRange,
    doStuffWithFirstRange,

    /* 3-5 */
    doStuffWithSecondRange,
    doStuffWithSecondRange,
    doStuffWithSecondRange,

    /* 6-7 */
    doStuffWithThirdRange,
    doStuffWithThirdRange
];

...但是如果值不是连续的数字,那么使用对象会更清楚.

...but if the values aren't contiguous numbers, it's much clearer to use an object instead.

这篇关于如何在使用 JavaScript 的 switch case 语句中使用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

layui实现laydate日历控件控制之前日期不可选择
具体实现代码如下: laydate.render({ elem: '#start_time', min:0, //,type: 'date' //默认,可不填}); 只要加一个min参数,就可以控制了。0表示之前的日期不可...
2024-11-29 前端开发问题
133

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301