2012-02-11 23 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