jquery在交换机案例中使用范围? [英] jquery Using ranges in switch cases?

查看:65
本文介绍了jquery在交换机案例中使用范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开关案例通常类似于

Monday: 
Tuesday: 
Wednesday: 
etc. 

我想使用范围。

from 1-12: 
from 13-19:
from 20-21:
from 22-30:

有可能吗?顺便说一句,我正在使用javascript / jquery。

Is it possible? I'm using javascript/jquery by the way.

推荐答案

你可以尝试滥用开关堕落行为

you could try abusing the switch fall through behaviour

var x = 5;
switch (x) {
    case  1: case 2: case 3: case 4: ...
        break;
    case 13: case 14: case 15: ...
        break;
    ...
}

这是非常详细的

或者你可以尝试这个

function checkRange(x, n, m) {
    if (x >= n && x <= m) { return x; }
    else { return !x; }
}

var x = 5;
switch (x) {
    case checkRange(x, 1, 12):
        //do something
        break;
    case checkRange(x, 13, 19):
    ...
}

这可以帮助您获得所需的行为。我在checkRange的else中返回!x 的原因是为了防止将 undefined 传递给交换机的问题声明。如果你的函数返回 undefined (如jdk的例子那样)并且你将 undefined 传递给交换机,那么第一个案例将是被执行。在任何相等的测试下,!x 保证不等于 x ,这就是switch语句选择哪种情况执行。

this gets you the behaviour you would like. The reason i return !x in the else of checkRange is to prevent the problem of when you pass undefined into the switch statement. if your function returns undefined (as jdk's example does) and you pass undefined into the switch, then the first case will be executed. !x is guaranteed to not equal x under any test of equality, which is how the switch statement chooses which case to execute.

这篇关于jquery在交换机案例中使用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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