Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript switch(true)

Tags:

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

like image 611
ntan Avatar asked May 04 '10 14:05

ntan


People also ask

What is true about the switch statement in JavaScript?

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.

Can I use switch true?

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.

What does JavaScript switch do?

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.

What is true about switch statement?

The statements in a switch continue to execute as long as the condition at the top of the switch remains true.


1 Answers

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.

like image 51
SLaks Avatar answered Sep 24 '22 12:09

SLaks