为什么我的switch语句在JavaScript中不起作用?[duplicate]

gijlo24d  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(134)

此问题在此处已有答案

Expression inside switch case statement(8个答案)
12小时前关门了。

var num = prompt("Enter your number");
switch (num) {
  case (num % 2 == 0):
    alert("the number is divisible by 2");
    break;
  case (num % 3 == 0):
    alert("the number is divisible by 3");
    break;
  default:
    alert("the number is not divisible by either 2 or 3");
    break;
 }

我试图得到能被2和3整除的数字,但在我的控制台上,我总是得到一个默认值。

pbgvytdp

pbgvytdp1#

使用if-then,而不是大小写

switch-case与具有多个值的表达式一起使用,例如switch(a),其后是针对a的各种值的一系列case选项。
你所拥有的是一系列你想要一个接一个测试的“条件”,为此,使用一系列的if-then

var num = prompt("Enter your number");
console.log(num)

if (num % 2 == 0) {
  alert("the number is divisible by 2");
} else if (num % 3 == 0) {
  alert("the number is divisible by 3");
} else {
  alert("the number is not divisible by either 2 or 3");
}
jpfvwuh4

jpfvwuh42#

您可以检查开关大小写的语法

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

相关问题