Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable passed to switch statement

This isn't the exact use scenario but I was wondering if it was possible to get the value passed to the switch statement without having to retype what is in the switch() part.

Example :

switch(someObject.withSomevalue*(Math.random()*11)) {
    case 1 : alert("one");
    // more cases here
    default: alert(theNumberThatWasPassed);
}

If we run the Math.random() again we'll get another random number that very well could meet one of the cases, so calling what aws called in the switch(x) statement isn't an option. I've been just storing it in a variable - x = someObject.withSomevalue*(Math.random()*11) - and then passing it to the switch that way switch(x), but I was wondering if it's possible to get the value passed to the switch within the switch statement.

like image 546
A Wizard Did It Avatar asked Jan 22 '23 03:01

A Wizard Did It


1 Answers

As everyone else pointed out you have to save it in a variable. But you can do the following in the expression though I do not know how cross browser compatible this is:

  switch(x = <your expression>){
    //
    default:alert(x);
  } 

and at least you save one line of code.

like image 75
Vincent Ramdhanie Avatar answered Feb 01 '23 15:02

Vincent Ramdhanie