开发者

jquery Using ranges in switch cases?

Switch cases are usually like

Monday: 
Tuesday: 
Wednesday: 
etc. 
开发者_运维问答

I would like to use ranges.

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

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;
    ...
}

which is very verbose

or you could try this

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):
    ...
}

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.


Late to the party, but upon searching for an answer to the same question, I came across this thread. Currently I actually use a switch, but a different way. For example:

switch(true) {
    case (x >= 1 && x <= 12):
        //do some stuff
        break;
    case (x >= 13 && x <= 19):
        //do some other stuff                
        break;
    default:
        //do default stuff
        break;
}

I find this a lot easier to read than a bunch of IF statements.


You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, a custom function can be written. Basically have the function test a give n value and return it if it's in range. Otherwise returned undefined or some other dummy value.

<script>

// Custom Checking Function..
function inRangeInclusive(start, end, value) {
    if (value <= end && value >= start)
        return value; // return given value
    return undefined; 
}

// CODE TO TEST FUNCTION
var num = 3;
switch(num) {
case undefined:
    //do something with this 'special' value returned by the inRangeInclusive(..) fn
    break;
case inRangeInclusive(1, 10, num):
    alert('in range');
    break;
default:
    alert('not in range');
    break;
}

</script>

This works in Google Chrome. I didn't test other browsers.


Nope, you need to use an if/else if series to do this. JavaScript isn't this fancy. (Not many languages are.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜