2012-02-11 22 views
0

在以下程序中,當只輸入空格時,它會顯示ex2例外value less than 5,而不是顯示ex4例外This is not a valid number,我無法理解它背後的邏輯。Javascript代碼

<html> 
<head> 
    <title></title> 
    <script type="text/javascript"> 
     function promptCheck() { 

      var val=prompt("Enter a Number between 5 and 10",""); 

      try { 
      if(val=="") { 
       throw "ex1"; 
      } 

      else if(val<5) { 
       throw "ex2"; 
      } 

      else if(val>10) { 
       throw "ex3"; 
      } 

      else if(isNaN(val)) { 
       throw "ex4"; 
      } 
      } 

      catch(err) { 
       if(err=="ex1") { 
        alert("You have not entered any value"); 
       } 
       if(err=="ex2") { 
        alert("Value less than 5"); 
       } 
       if(err=="ex3") { 
        alert("Value greater than 10"); 
       } 
       if(err=="ex4") { 
        alert("This is not a valid number"); 
       } 
      } 

     } 
    </script> 
</head> 

<body> 
    <input type="button" value="Bring Mouse on Me!" onmouseover="promptCheck()" /> 
</body> 
</html> 

回答

2

這是因爲只用空格字符串被視爲空字符串,它被轉換爲0

所以

" "*1 // => 0 

你需要做的是事前分析值:

var value = parseInt(val, 10); // would be NaN in case of empty string 
+0

是啊...解決了麻煩問題! – sandbox 2012-02-11 14:55:59

2

在數字上下文中,空格轉換爲零。和零明顯低於5

alert(' ' * 1); // Shows 0 

爲了解決這個問題,你可以使用parseFloat,這將打印NaN的空間。
另一種選擇是使用正則表達式,以確保輸入由整數:

var val = prompt("Enter a Number between 5 and 10", ""); 
val = /\d+/.exec(val); // Numbers if valid, null otherwise 

// OR, instead of the previous line: 
if (/\D/.test(val) { // If the input contains a non-digit character, error. 
    throw "ex4"; 
} else ... 

對於字符串到數字的轉換,見this comparison of number-conversion methods。你可以看到給定輸入會發生什麼。

+0

應該補充的是重新排序'else's可以解決問題。 – moteutsch 2012-02-11 14:39:43

+0

好吧......夠公平的。現在應用什麼邏輯來捕捉白色空間? – sandbox 2012-02-11 14:41:05

+0

@moteutsch這不會解決問題,因爲'isNaN'會檢查是否爲空白,即零,是否爲'NaN'。這是錯誤的。 – 2012-02-11 14:41:23