简体   繁体   English

如何使用切换大小写在javascript中找到两个数字之间的最大值?

[英]How to find maximum between two numbers in javascript using switch case?

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;
}

Logical operations return boolean on Javascript. 逻辑操作在Javascript上返回布尔值。

document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console. document.write将HTML表达式或JavaScript代码写入文档,console.log在浏览器控制台上打印结果。

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

switch (with a lower case s) uses strict comparison === so the value of a boolean like 11 > 10 will never === 0 or 1 . switch (带有小写s)使用严格的比较===因此像11 > 10这样的布尔值永远不会=== 01

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. 如果由于某些原因给了您数字,您可以将它们显式地转换为布尔值,例如case !!0: :,但是这开始变得有些困难。

If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability. 如果您的目标是找到两个数字中的最大值,那么Math.max(num1, num2)很难获得可读性。

You would just use the greater than / less than inside of the switch statement. 您只需要在switch语句内部使用大于/小于。

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

You could use something simple as Math.max(5, 10) ; 您可以使用简单的东西作为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: 或者,如果您绝对“必须”使用switch statement ,则可以尝试如下操作:

 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'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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