创建一个函数并且无法理解如何在switch case中进行比较,因此NaN === case变为true并返回“Input number is Number.NaN”;
function whatNumberIsIt(n){
var str;
switch (n) {
case Number.MAX_VALUE : str = "Input number is Number.MAX_VALUE";
break;
case Number.MIN_VALUE : str = "Input number is Number.MIN_VALUE";
break;
case Number.NaN : str = "Input number is Number.NaN";
break;
case -Infinity : str = "Input number is Number.NEGATIVE_INFINITY";
break;
case Infinity : str = "Input number is Number.POSITIVE_INFINITY";
break;
default : str = "Input number is " + n;
}
return str;
}
whatNumberIsIt(NaN)
答案 0 :(得分:2)
在switch语句中比较isNaN
,检查是否为false。这是代码:
function whatNumberIsIt(n){
var str;
/**
* The !isNaN(n) here is really the secret sauce.
* This means the value has to be a real number before comparisons will
* even happen. That's why we're able to compare "false" in the switch... otherwise
* this code wouldn't work.
*/
switch (!isNaN(n) && n) {
case Number.MAX_VALUE :
str = "Input number is Number.MAX_VALUE";
break;
case Number.MIN_VALUE :
str = "Input number is Number.MIN_VALUE";
break;
case false :
str = "Input number is Number.NaN";
break;
case -Infinity :
str = "Input number is Number.NEGATIVE_INFINITY";
break;
case Infinity :
str = "Input number is Number.POSITIVE_INFINITY";
break;
default : str = "Input number is " + n;
}
return str;
}
console.log( whatNumberIsIt("String") );
console.log( whatNumberIsIt(NaN) );
console.log( whatNumberIsIt(1) );
console.log( whatNumberIsIt(Infinity) );
console.log( whatNumberIsIt(-Infinity) );
小提琴:https://jsfiddle.net/87o83q2q/
这是您应该期望的输出:
Input number is Number.NaN
Input number is Number.NaN
Input number is 1
Input number is Number.POSITIVE_INFINITY
Input number is Number.NEGATIVE_INFINITY