最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to find maximum between two numbers in javascript using switch case? - Stack Overflow

programmeradmin4浏览0评论

I am trying to run with this code block but it does not work

Switch (num1>num2) {
case 0:
  document.write(num2);
  break;
case 1:
  document.write(num1);
 break;
}

I am trying to run with this code block but it does not work

Switch (num1>num2) {
case 0:
  document.write(num2);
  break;
case 1:
  document.write(num1);
 break;
}
Share Improve this question edited Aug 11, 2018 at 2:37 Tieson T. 21.3k6 gold badges81 silver badges96 bronze badges asked Aug 11, 2018 at 2:25 Piyush SinghPiyush Singh 211 silver badge4 bronze badges 2
  • 2 num1>num2 can never match value of either of those cases – charlietfl Commented Aug 11, 2018 at 2:32
  • 1 Your code is basically document.write(Math.max(num1, num2)). – Angel Politis Commented Aug 11, 2018 at 2:46
Add a ment  | 

4 Answers 4

Reset to default 2

You could use something simple as Math.max(5, 10);

const numOne = 5;
const numTwo = 10;

console.log(`Bigger number is: ${Math.max(numOne, numTwo)}`);

Or if you absolutely 'have to' use switch statement, you can try something like this:

const numOne = 5;
const numTwo = 10;

switch(true) {
    case (numOne > numTwo):
        console.log(`Bigger number is ${numOne}`);
        break;
    case (numOne < numTwo):
        console.log(`Bigger number is ${numTwo}`);
        break;
    case (numOne === numTwo):
        console.log(`${numOne} is equal to ${numTwo}`);
        break;
     default: console.log(false, '-> Something went wrong');
}

Logical operations return boolean on Javascript.

document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console.

   switch (num1>num2) {
      case true:
          console.log(num1);
       break;
       case false:
           console.log(num2);
       break;
    }

switch (with a lower case s) uses strict parison === so the value of a boolean like 11 > 10 will never === 0 or 1.

You need to test for the boolean if you want to do it this way:

let num1 = 10
let num2 = 20

switch (num1>num2) {
    case false:
      console.log(num2);
      break;
    case true:
      console.log(num1);
     break;
    }
    
    

If for some reason you were given numbers you could explicitly cast them to booleans with something like case !!0: but that starts to get a little hard on the eyes.

If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability.

You would just use the greater than / less than inside of the switch statement.

var x = 10;
var y = 20;

switch(true) {
    case (x > y):
        console.log(x);
        break;
    case ( y > x):
        console.log(y);
        break;
}

发布评论

评论列表(0)

  1. 暂无评论