Language Syntax for Switch (Javascript and C #) and Select ... Case (VBScript) - Combining Cases

In VB, if I wanted to match case register, it would look like this:

Select (somevalue)
  Case 1, 2, 3:
    Do Something
End Select

In C # and Javascript

switch (someValue) {
  case 1:
  case 2:
  case 3:
     //dosomething
     break;
}

However, this runs without error in Javascript

switch (someValue) {
  case 1, 2, 3:
     break;
}

But does not do what is expected. What is this actually doing?

The reason I'm asking is because if I hover over 1, 2 or 3 in firebug, it indicates the clock is false. It is so clear what the code evaluates, but what it evaluates.

+3
source share
3 answers

The Javascript comma operator evaluates both of its operands in order from left to right, returning the rightmost one. So you essentially wrote

switch (someValue) {
    case 3:
        break;
}
+5

:

switch(true) {
  case (somevalue <= 3): /* action if <= 3 */ break;
  case (somevalue <= 6): /* action if <= 6 */ break;
  //[etc]
  default: 'no action' 
}

: , :

Number.prototype.In = function(){
    var i = -1, args = arguments;
    while (++i<args.length){
         //use float for all numbers
         if (parseFloat(this) === parseFloat(args[i])){
         return true;
        }
    }
    return false;
};

:

switch(true) {
  case somevalue.In(1,2,3):   /* action if 1,2,3 */ break;
  case somevalue.In(6,10,14): /* action if 6,10,14 */ break;
  //[etc]
  default: 'no action' 
}

. O'Reilly - switch

+3

Mdarvi defeated me, nevertheless he nailed it,

<script type="text/javascript">
var x = 5;
switch (x)
{
  case 5, 6, 7:
    document.write("<b>This should work on 5, 6 or 7.</b>");
    break;
  case 0:
    document.write("<b>This should work on 0.</b>");
    break;
}
</script>

.. writes the first case only when x == 7.

+2
source

Source: https://habr.com/ru/post/1780515/


All Articles