简体   繁体   中英

switch case doesn't works

my problem is I want to scroll to a specified div (#morg, #vorm, #nachm, #abe) and it always goes to the default statement.

Why that?

function scrollToCarret(listview) {
var hour = new Date();
var hours = hour.getHours();

console.log(listview + hours);
switch(hours) {
    case hours < "8":
        console.log("< 8");
      break;
    case hours < "13":
        console.log("< 13");
      break;
    case hours < "18":
        console.log("< 18");
      break;
    case hours < "24":
        console.log("< 24");
      break;
    default:
        console.log("faiL");
    }
}

Thanks

switch / case in JavaScript doesn't work like that. It always tests for equality with each of the case s.

What it does is converting the conditions ( hours < "18" , etc.) to booleans because it requires a scalar value for each case . Then the value of hours is compared to each of the values in the case s. Since no matching one can be found (because they're true and false ) it jumps to default .

Basically what is run is the following:

if (hours == (hours < "8") {
  ...
} else if (hours == (hours < "13") {
  ...
} else if (hours == (hours < "18") {
  ...
} else if (hours == (hours < "24") {
  ...
}

Each case is compared against the expression you gave in switch , in this case that's hours .

Yes, I really miss VB's Select Case sometimes too. But C-like languages usually have nothing like it (PowerShell does, though ;-)).

Switch statements aren't used for anything other than equality with the selector.

In your code, the selectors are the result of each of your logical expressions. The following lines are identical, if we assume that hours = 8:

case hours < 8:
case (hours < "8"):
case (8 < "8"):
case false:

The switch statement works by comparing the first expression (the one following the switch keyword) to those following the case keywords.

Therefore, in your code your are basically comparing hours (expected to be an integer) to hours < "8" (a boolean), which can produce unexpected results.

What you want to do is change :

switch (hours) {
    case hours < "8":
        ...
    case hours < "13":
        ...
    case hours < "18":
        ...
    case hours < "24":
        ...
    default:
        ...
}

To:

if (hours < 8) {
    ...
} else if (hours < 13) {
    ...
} else if (hours < 18) {
    ...
} else if (hours < 24) {
    ...
} else {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM