Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jump to a different switch case based on conditon, like a goto

I need to move from one case to another case based on the condition. For example, this is my code:

switch (req.method) {
  case 'GET':
    alert('GET METHOD');
    break;
  case 'POST':
    alert('POST METHOD');
    break;
  case 'PUT':
    alert('PUT METHOD');
    break;
  default:
    res.end();
}

In the above code, in the POST case I need to check, for example if(A === B), then go to the PUT case like that. How to do this?

like image 819
thevan Avatar asked Jul 23 '14 07:07

thevan


People also ask

Can goto be used in switch case?

@The Smartest: A switch statement in itself can already have plenty of goto s, but they are named differently: Each break is a goto. @chiccodoro That's nothing, actually each case is a label and switch essentially is a goto . Each break is a goto , but also each continue is a goto too.

Can goto statement go outside of switch?

Yes, it does.

How do you use a conditional statement in a switch case?

switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. The switch statement is closely related to a conditional statement containing many else if blocks, and they can often be used interchangeably.

Can a switch case have a conditional?

The switch-case condition works as a sequence of if-else blocks. Whenever the work of our program depends on the value of one variable, instead of making consecutive conditions with if-else blocks, we can use the conditional switch statement.


1 Answers

Make a conditional recursive

function checkMethod(method) {
    switch (method) {
        case 'GET':
            alert('GET METHOD');
            break;
        case 'POST':
            alert('POST METHOD');
            checkMethod('PUT'); // here stand the pros of a function
            break;
        case 'PUT':
            alert('PUT METHOD');
            break;
        default:
            res.end();
    }
}
like image 87
Salathiel Genèse Avatar answered Sep 28 '22 15:09

Salathiel Genèse