switch 语句不执行相应的块
Switch Statement Not Executing Corresponding Blocks
这是我的代码
var randomNumber = Math.ceil(100 * Math.random());
switch (randomNumber) {
case (randomNumber < 20):
console.log("The number is less than 20");
break;
case (randomNumber => 20 && randomNumber < 50):
console.log("The number is between 20 and 50");
break;
case (randomNumber => 50 && randomNumber < 75):
console.log("The number is between 50 and 75");
break;
default:
console.log("The number is greater than 75");
break;
}
console.log(randomNumber);
第一部分简单地声明一个新绑定并为其分配一个介于 1 和 100 之间的随机整数值。
第二部分,switch 语句,应该根据条件、随机数绑定的值发送特定消息。
出于某种原因——我不确定为什么——它只执行对应于 default
关键字的代码。当然,它还会执行最后一条语句,将绑定的值打印到浏览器控制台。
我做错了什么?
switch
statement uses a strict comparison 并且您需要检查 true
。
然后你可以只检查上限,因为你已经检查了下限。
var randomNumber = Math.ceil(100 * Math.random());
switch (true) {
case randomNumber < 20:
console.log("The number is less than 20");
break;
case randomNumber < 50:
console.log("The number is between 20 and 50");
break;
case randomNumber < 75:
console.log("The number is between 50 and 75");
break;
default:
console.log("The number is greater than 75");
break;
}
console.log(randomNumber);
这是我的代码
var randomNumber = Math.ceil(100 * Math.random());
switch (randomNumber) {
case (randomNumber < 20):
console.log("The number is less than 20");
break;
case (randomNumber => 20 && randomNumber < 50):
console.log("The number is between 20 and 50");
break;
case (randomNumber => 50 && randomNumber < 75):
console.log("The number is between 50 and 75");
break;
default:
console.log("The number is greater than 75");
break;
}
console.log(randomNumber);
第一部分简单地声明一个新绑定并为其分配一个介于 1 和 100 之间的随机整数值。
第二部分,switch 语句,应该根据条件、随机数绑定的值发送特定消息。
出于某种原因——我不确定为什么——它只执行对应于 default
关键字的代码。当然,它还会执行最后一条语句,将绑定的值打印到浏览器控制台。
我做错了什么?
switch
statement uses a strict comparison 并且您需要检查 true
。
然后你可以只检查上限,因为你已经检查了下限。
var randomNumber = Math.ceil(100 * Math.random());
switch (true) {
case randomNumber < 20:
console.log("The number is less than 20");
break;
case randomNumber < 50:
console.log("The number is between 20 and 50");
break;
case randomNumber < 75:
console.log("The number is between 50 and 75");
break;
default:
console.log("The number is greater than 75");
break;
}
console.log(randomNumber);