Skip to content Skip to sidebar Skip to footer

Javascript Switch Statement

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

Solution 1:

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.

Solution 2:

Try this:

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

The -0 will force (coerce) it to treating your value as an integer without changing the value, and it's much shorter than parseInt.

Solution 3:

Are you sure the ResultType is an integer (e.g. 0) and not a string (e.g. "0")?

This could easily explain the difference in behaviour

Solution 4:

It looks like changing it to parseInt(msg.ResultType) has forced the JavaScript engine to properly treat it as an integer. Thanks for the help.

Solution 5:

First thing I noticed is that in two of the three cases, you're calling .val() and in the third you're calling .text().

If you tried changing the case statements to strings instead of ints, then the only thing I can think of is that you're hitting an exception somewhere along the line possibly caused by accessing an undefined variable.

Post a Comment for "Javascript Switch Statement"