Get the variable passed to the switch statement

This is not an exact use case, but I was wondering if it is possible to get the value passed to the switch statement without re-entering what is in the switch() .

Example:

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

If we run Math.random() again, we get another random number that one of the cases might very well meet, so the call that aws called in switch (x) is not an option. I just saved it in a variable - x = someObject.withSomevalue*(Math.random()*11) - and then passed it to the switch in this way switch(x) , but I was wondering if it is possible to get the value passed to the switch in the switch statement .

+4
source share
5 answers

This is the same as the query if you can find the values ​​for if(Math.random()){...} . The answer is no, because these are language constructs, not functions.

+2
source

Like everyone else, you must save it in a variable. But you can do the following in an expression, although I don’t know how cross-browser compatible with this:

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

and at least you save one line of code.

+5
source

Just write it to a variable in front of the switch and use this variable.

  var myValue = someObject.withSomevalue * (Math.random () * 11);
 switch (myValue) {
     case 1: alert ("one");
     // more cases here
     default: alert (myValue);
 } 
+2
source

I would say that it is best to do what you are doing now and write it to a variable before the switch statement. Is there a reason you don't want to do this other than saving a line of code?

0
source

Interesting ... OP, I'm trying to look at your thought process. Maybe just write the code, what do you think it should look like (ignoring that it will not work in the first place).

update:

At least in C / C ++, you can simply create another block to have access only to the var variable in the switch:

 ... { var mySwitchVar = blah; switch(mySwitchVar) { case blah blah blah: default blah blah: } } ...
... { var mySwitchVar = blah; switch(mySwitchVar) { case blah blah blah: default blah blah: } } ... 
0
source

All Articles