gpt4 book ai didi

javascript - 开关盒中的 JS NaN 比较

转载 作者:行者123 更新时间:2023-11-29 14:41:12 25 4
gpt4 key购买 nike

创建一个函数,无法理解我如何在 switch case 中进行比较,所以 NaN === case 为真并返回“输入数字是 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)

最佳答案

比较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) );

fiddle :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

关于javascript - 开关盒中的 JS NaN 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com