Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript switch statement

Tags:

javascript

I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected.

switch (msg.ResultType) {
  case 0:
    $('#txtConsole').val("Some Val 0");
    break;
  case 1:
    $('#txtConsole').val("Some Val 1");
    break;
  case 2:
    $('#txtConsole').text("Some Val 2");
    break;
}

The ResultType is an integer value 0-2 and I can see that in FireBug. In all cases, the switch transfers control to the final break statement which means all the logic is completely skipped. What am I missing?

like image 433
Joe Brinkman Avatar asked Oct 30 '08 13:10

Joe Brinkman


People also ask

What is a switch statement in JavaScript?

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 switch statement example?

So, printf(“2+3 makes 5”) is executed and then followed by break; which brings the control out of the switch statement. Other examples for valid switch expressions: switch(2+3), switch(9*16%2), switch(a), switch(a-b) etc.

Can we use switch case in JS?

The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task.

What is a switch () statement?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.


1 Answers

I'm sure that a switch uses === for comparison in Actionscript and since JS and AS both follow the ECMAScript standard, I guess the same applies to JS. My guess is that the value is not actually a Number, but perhaps a String.

You could try to use parseInt(msg.ResultType) in the switch or use strings in the cases.

like image 155
Juan Pablo Califano Avatar answered Sep 22 '22 19:09

Juan Pablo Califano