Using isNaN () to determine the number
The isNaN () function checks whether its arguments are non-numeric values.
Description
The isNaN () function can be used to determine whether its argument is NaN, which represents an illegal number (such as the result of being 0 apart).
If the result of Nan being compared to any value (including itself) is false, you cannot use the = = or = = operator to determine whether a value is NaN. Because of this, the isNaN () function is required.
Test:
| The code is as follows |
Copy Code |
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
|
Cases
Calculates the parameter, and returns True if the value is NaN (not a number). This function can be used to check whether a mathematical expression was successfully evaluated as a number.
| The code is as follows |
Copy Code |
if (isNaN (Document.login.imgcode.value)) { Alert (' Authentication code must be a number! ') Document.login.imgcode.focus (); return false; } if (!isnum (document.getElementById ("Prjsum"). Value) { Alert ("Cost can only be a number"); document.getElementById ("Prjsum"). focus (); return false;
} |
use regular expressions to check numbers
It's a good one. The code that is used to check whether the character entered is a number is not a common way of writing.
| The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" > <meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/> <title>untitled document</title> <body> <input type= "text" id= "Myinput" value= ""/> <input type= "button" value= "OK" id= "MyButton"/> </body> <script language= "JavaScript" type= "Text/javascript" > function $ (obj) { return Document.getelementbyidx (obj); } function Checkisinteger (str) { If empty, the checksum is passed 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 ("Success"); }else{ Alert ("Only a number"); } } </script> |