Javascript switch statement- very simple, what am I doing wrong?
I'm sure there must be a really simple answer to this, but at the risk of sounding stupid- I can't get this switch statement to work. The input var, 'status' can be either 'public' or 'draft', and I can assure you it is only holding one of those two values as I have alerted it out at various stages, and anyway, the if statement here works. Take a look:
function switch_status(status){
if (status == 'public'){
return false;
} if (status == 'draft') {
return true;
}
^This works, but replacing the 'if' with this 'switch' statement below doesn't work.
switch(status){
case 'public':
return false;
case 'draft':
return true;
}
}
The first one to provide me with the inevitable embarrassingly simple answer wins my accolade!
EDIT: Here is my full 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(statu开发者_运维知识库s){
// if (status == 'public'){
// return false;
// } if (status == 'draft') {
// return true;
// }
switch(status){
case 'public':
return false;
case 'draft':
return true;
}
}
You're passing status
as an array of one string (the result of slice
) rather than as just a string.
When you check equality between your array and your string, it appears that coercion is causing the equality check to work. But coercion doesn't happen in a switch statement.
If I change
status = fullClass.split(' ').slice(-2,-1);
to
status = fullClass.split(' ').slice(-2,-1)[0];
then it works fine.
I suspect this problem is occuring due to type conversion.
Javascipt is generally a loosely typed language. The if statement you used earlier used a loose ==
comparison. This worked just fine.
However, switch statements are a different matter. For the case to be a match, the data types must match. In other words, the status
must be converted to a string before it is passed to the switch statement.
I used a .each in a jquery loop and compared value to 'this'; I could clearly see that 'this' had the correct value if I used console.log. It worked in the if/else logic but failed in the switch/case logic.
The solution is:
var obj = this.toString();
switch(obj){
case 'one': ...
case 'two': ...
}
By forcing the 'this' to a string type, the logic in the switch now works.
精彩评论