javascript 判斷變數是否為數字執行個體

來源:互聯網
上載者:User

利用isNaN()判斷數字

isNaN() 函數用於檢查其參數是否是非數字值。

說明:
 

isNaN() 函數可用於判斷其參數是否是 NaN,該值表示一個非法的數字(比如被 0 除後得到的結果)。

如果把 NaN 與任何值(包括其自身)相比得到的結果均是 false,所以要判斷某個值是否是 NaN,不能使用 == 或 === 運算子。正因為如此,isNaN() 函數是必需的。


測試:

 代碼如下 複製代碼

 
document.write(isNaN(123)); // false
document.write(isNaN(-1.23)); // false
document.write(isNaN(5-2)); // false
document.write(isNaN(0)); // false
document.write(isNaN("Hello")); // true
document.write(isNaN("2005/12/12")); // true
document.write(isNaN("6/2")); // true
document.write(isNaN("3")); // false


算參數,如果值為 NaN(非數字),則返回 true。此函數可用於檢查一個數學運算式是否成功地計算為一個數字。

 代碼如下 複製代碼

if(isNaN(document.login.imgcode.value)){
   alert('驗證碼必須是數字!')
   document.login.imgcode.focus();
   return false;
}

if(!isNum(document.getElementById("prjSum").value)){
    alert("造價只能是數字");
    document.getElementById("prjSum").focus();
    return false;
   
}


利用Regex為檢查數字

不錯的一個用正則檢測輸入的字元是否為數位代碼,也是一種並不常見的寫法

 代碼如下 複製代碼
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
        <title>Untitled Document</title>
    </head>
    <body>
        <input type="text" id="myInput" value="" />
        <input type="button" value="確定" id="myButton" />
    </body>
</html>
        <script language="JavaScript" type="text/javascript">
        function $(obj){
            return document.getElementByIdx(obj);
        }
        function checkIsInteger(str)
        {
                //如果為空白,則通過校正
                if(str == "")
                return true;
               if(/^(-?)(d+)$/.test(str))
               return true;
             else
               return false;
         }
         String.prototype.trim = function()
        {
                return this.replace(/(^[s]*)|([s]*$)/g, "");
        }
        $("myButton").onclick=function(){
           
            if(checkIsInteger($("myInput").value.trim())){
                alert("成功");
            }else{
                alert("只能是數字");
            }
        }
        </script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.