Javascript switch statement - very simple, what am I doing wrong?

I'm sure there should be a very simple answer to this question, but at the risk of sounding silly - I can't get this switch statement to work. The input var, 'status' can be either "public" or "draft", and I can assure you that it only holds one of these two values, since I warned about this at different stages, and in any case, the if statement here works, see:

function switch_status(status){ if (status == 'public'){ return false; } if (status == 'draft') { return true; } 

^ This works, but replacing "if" with this "switch" statement below does not work.

  switch(status){ case 'public': return false; case 'draft': return true; } } 

The first one to give me the inevitable awkwardly simple answer will receive my reward!

EDIT: Here is my complete code -

  $('.status').live('click', function(){ fullClass = $(this).attr('class'); id = fullClass.split(' ').slice(-1); status = fullClass.split(' ').slice(-2,-1); var newStatus = switch_status(status); alert(newStatus); }); function switch_status(status){ // if (status == 'public'){ // return false; // } if (status == 'draft') { // return true; // } switch(status){ case 'public': return false; case 'draft': return true; } } 
+4
source share
3 answers

You pass status as an array of one string (the result of slice ), and not as a string.

When you check for equality between your array and your string, it seems that coercion causes an equality check. But coercion does not occur in the switch statement.

If i change

 status = fullClass.split(' ').slice(-2,-1); 

to

 status = fullClass.split(' ').slice(-2,-1)[0]; 

then it works great.

+4
source

I suspect this problem is due to type conversion.

Javascipt is usually a freely typed language. The if statement you used earlier used the free == comparison. This worked perfectly.

However, switch statements are another matter. In order for the case to be a match, the data types must match. In other words, status must be converted to a string before it is passed to the switch statement.

+1
source

I used .each in a jquery loop and compared the value with 'this'; I could clearly see that 'this' has the correct meaning if I used console.log. It worked in if / else logic, but did not work in switch / case logic.

Decision:

var obj = this.toString ();

 switch(obj){ case 'one': ... case 'two': ... } 

Forcing 'this' to a string type, the logic in the switch now works.

0
source

Source: https://habr.com/ru/post/1332232/


All Articles