2016-06-27 72 views
3

製作一個函數並且不能理解如何在開關盒中進行比較,所以NaN ===的情況變爲真,並返回「輸入號爲Number.NaN」;JS開關盒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) 
+1

可以插入在默認情況下的檢查。使用'isNaN()',你可以顯示一個不同的字符串,如果它是'NaN'。 –

+0

@Teemu謝謝,也嘗試過這一個,但仍然沒有工作( @MohitBhardwaj在這種情況下,我需要我的默認情況下除了max_value,min_value,無限和南等所有其他情況。 –

+0

@Teemu你可以運行一個函數你會發現在你的情況下(case!+ n:str ='輸入數字是NaN'; break;)它不會去使用它並返回默認情況 –

回答

2

比較isNaN在switch語句中,檢查是否爲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 
+1

我真的相信我試過假的情況。它的工作原理!謝謝 –

+0

這不僅僅是假的,你有將比較運算符添加到switch語句本身。看看我編輯過的有關'!isNaN(n)'的註釋......這就是爲什麼它可以工作。沒有它,它將繼續失敗。 –

+0

之前沒有注意到,但現在我完全困惑。你能解釋一下我的開關(!isNaN(n)&& n)以及它如何處理假案件? –