【发布时间】:2020-08-03 10:12:04
【问题描述】:
我正在运行两个看似相同的语句来检查一个数字是正数、负数还是零。
if 语句返回预期结果。
switch 语句始终返回默认值。
为什么?
在这个例子中,我传递了“2”(type: number),然后在if 语句中得到+,在? 语句中得到?。
// Verify whether a number is positive, negative or Zero:
function myFuncIf(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
if (y > 0) {
return "+";
} else if (y < 0) {
return "-";
} else {
return "?";
}
}
function myFuncSwitch(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
switch (y) {
case (y > 0):
result = "+";
break;
case (y < 0):
result = "-";
break;
default:
result = "?";
}
return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));
【问题讨论】:
-
switch ... case ...语句不是这样工作的:"switch语句评估一个表达式,将表达式的值与case子句匹配,并且执行与该案例相关的语句,以及匹配案例后面的案例中的语句。” (Source)
标签: javascript