Switch statements and ranges of numbers

不想你离开。 提交于 2019-12-19 00:16:19

问题


How do you craft a switch statement in as3 to make the case apply to an entire range of numbers?

if (mcPaddle.visible == true)
{
    switch (score)
    {
        case  10://10 to 100
            myColor.color = 0x111111;
            break;
        case 110://110 to 1000
            //etc etc
            break;
    }
}

I've tried multiple ways to make the case apply for all numbers between 10-100, and 110-1000, but can't seem to find a way to do it, and I can't find the proper syntax for such a thing in as3.


回答1:


You can use a switch block :

var score:Number = 123;

switch(true){

    case score > 120 && score < 125 :
        trace('score > 120 && score < 125');
        break;

    case score > 100 && score < 140 :
        trace('score > 100 && score < 140');
        break;

    case score == 123 :
        trace('score == 123');
        break;

}
//score > 120 && score < 125



回答2:


switch statements just restatements of if (a = b) or (a = c) or (a = d) ... type constructs. THey're not intended for ranges. You can somewhat simulate it using fallthroughs:

switch (score) {
   case 10:
   case 11:
   case 12:
   case 13:
   case etc...
        blah blah blah
        break;
}

but that's a ludicrously dumb way to go. Much easier/terser to use a regular if()




回答3:


ActionScript's switch statement doesn't work with ranges, but you can easily do it with if/else chains:

if (score >= 10 && score <= 100)
{
    //10 - 100
}
else if (score <= 110)
{
    //101 - 110
}
else if (score <= 1000)
{
    //111 - 1000
}



回答4:


For those looking for how to use this in HTML/jQuery, I've used @OXMO456's answer to create this simple pen: http://codepen.io/anon/pen/jHFoB

You just have to set the var normally and remove the lines starting with trace.

Ps. I'm adding this as an answer since I don't have enough rep to comment on his. If anyone can, please move/copy this there. Thanks!



来源:https://stackoverflow.com/questions/5839937/switch-statements-and-ranges-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!