简体   繁体   中英

Why "Switch" doesn't work properly with comparison of two variables?

I wonder why the switch case is ignored, and the comparison of two variables doesn't even begin. In Chrome debugger, the switch operation just is being skipped.

 let input = 5; let generatedNum = 20; switch(generatedNum) { case input === generatedNum: alert("The numbers match"); break; case input < generatedNum: alert("Input is less"); break; case input > generatedNum: alert("Input is bigger"); break; }

The usage of switch..case construct is the following:

switch (variable) {
  case value1:
    block1
  case value2:
    block2
  case value3:
    block3
}

In your case, you want to use a simple if..else construct:

let input = 5;

let generatedNum = 20;

if (input === generatedNum)
  alert("The numbers match");

else if (input < generatedNum)
  alert("Input is less");

else if (input > generatedNum) // technically, you can put just "else" here
  alert("Input is bigger");

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