How do you have a NaN case in a switch statement?

后端 未结 4 1453
滥情空心
滥情空心 2021-02-04 12:20

Since NaN === NaN evaluates to false, is it possible to add a NaN case to a switch statement?

For example, let\'s say

4条回答
  •  太阳男子
    2021-02-04 12:31

    @helmus's answer is correct and is a good solution.

    However, you can maintain the NaN case if you use strings:

    switch(x+''){
        case "1":
        case "2":
        case "4":
            doSomething();
            break;
        case "NaN":
            doSomethingElse();
            break;
        default:
            doADifferentThing();
            break;
    }
    

提交回复
热议问题