Hi i am trying to handle an ajax json response
here is my code
success: function (j) { switch(true) { case (j.choice1): alert("choice2"); break; case (j.choice2): alert("choice2"); break; default: alert("default"); break; } }
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
The fundamental principle of the switch true pattern is that the switch statement will match against expressions as well as values. An expression in a case will be evaluated before matching. If the expression in your case evaluates to true - it will be matched.
You probably know that the switch statement allows matching an expression (the switch ) against different values (the case ), so using switch(true) may seem absurd: Well, that's not true. You can match against values as well as expressions.
Definition and Usage. The switch statement executes a block of code depending on different cases. The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed.
The statements in a switch continue to execute as long as the condition at the top of the switch remains true.
It works for me:
var a = 0, b = true; switch(true) { case a: console.log('a'); break; case b: console.log('b'); break; }
However, the case
labels must be equal to true
, not jut implicitly true.
Also, only the first case that evaluates to true
will execute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With