To process multiple cases in a switch statement in javascript at once

Asked 2 years ago, Updated 2 years ago, 29 views

I want to process several values in one, but it doesn't work well because I wrote in the case. What should I do?


function daysInMonth( month ){
  switch(month){
    case 2:
      return 28;
      break;
    case 4,6,9,11:
      return 30;
    default:
      return 31;    }
}

console.log(daysInMonth(9));
//=> 31

javascript switch문

2022-09-22 19:52

2 Answers

To process multiple values at once in a switch statement in javascript, you must write down the case several times as shown below.

function daysInMonth( month ){
  switch(month){
    case 2:
      return 28;
    case 4:
    case 6:
    case 9:
    case 11:
      return 30;
    default:
      return 31;    }
}

console.log(daysInMonth(9));
// // => 30


2022-09-22 19:52

I don't know the intention to process multiple values at once in the switch statement.

In this case, it seems better to treat it as an if statement.

As far as I know, the switch case is used for processing by case.


2022-09-22 19:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.