10

Can I use intervals in a switch statement?

Like

switch (parseInt(troops[i])) {
                case <10:
                    editbox.style.fontSize = "13px";
                    break;
                case <100:
                    editbox.style.fontSize = "12px";
                    break;
                case <1000:
                    editbox.style.fontSize = "8px";
                    editbox.size = 3;
                    //editbox.style.width = "18px";
                    break;
                default:
                    editbox.style.fontSize = "10px";
            }

???

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
FernandoSBS
  • 655
  • 5
  • 12
  • 23

3 Answers3

24

This should work though:

var j = parseInt(troops[i]);
switch (true) {
            case (j<10):
                editbox.style.fontSize = "13px";
                break;
            case (j<100):
                editbox.style.fontSize = "12px";
                break;
            case (j<1000):
                editbox.style.fontSize = "8px";
                editbox.size = 3;
                //editbox.style.width = "18px";
                break;
            default:
                editbox.style.fontSize = "10px";
        }
Cahit
  • 2,484
  • 19
  • 23
  • clever! (this is filler, 15 char min argh!) – Rob Jun 08 '10 at 01:07
  • 2
    To be safe, you should include a radix argument when using parseInt(). So: `parseInt(troops[i],10)` can avoid some maddening bugs. For example, if troops[i] happens to have a value of "010", js guesses the radix as 2. Probably not what you want. – Ken Redler Jun 08 '10 at 04:48
3

No. switch can be used only with discrete values. For ranges you'll have to use an if statement.

var val = parseInt(troops[i]);
if (val < 10) {
    editbox.style.fontSize = "13px";
} else if (val < 100) { 
    // ...
} else {
}
VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
2

Sometimes a switch is too much like work

var j= parseInt(troops[i]),
val= j<10? 13: j<100? 12: j<1000? 8: 10;

editbox.style.fontSize= val+'px';
if(val== 8) editbox.size= 3;
kennebec
  • 102,654
  • 32
  • 106
  • 127