javascript - 开关盒中的 JS NaN 比较

标签 javascript types nan

创建一个函数,无法理解我如何在 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/

相关文章:

python - StandardScaler -ValueError : Input contains NaN, 无穷大或对于 dtype ('float64' 来说值太大)

javascript - 如何解决比较变量时它在 JavaScript 中变为未定义的问题?

javascript - wix/react-native-navigation V2 | wix/react-native-navigation V2 |在第二个屏幕中设置根底部选项卡

javascript - 如何制作可折叠菜单 jQuery Mobile

java - 如何为具有未确定的 "?"值类型的 Java 通用映射添加值

go - 保存类型以供以后反射

javascript - 在另一个 AJAX 调用后延迟返回

javascript - 关于 WebGL 的一些问题

swift - 在结构内指定 Hashable 类型约束

python - 以间隔对包含 np.nan 的值进行分组