判断输入的数是否为数字,不使用isNaN

时间:2023-01-26 23:17:49

虽然不使用 isNaN ,但使用了 Math 的一些方法。

<!--
Author: XiaoWen
Create a file: 2016-12-08 11:14:34
Last modified: 2016-12-08 11:45:41
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>判断是不是数字</title>
</head>
<body>
<input type="text"><input type="button" value="判断">
<script>
  var ipt=document.getElementsByTagName("input");
  //不使用isNaN的方式
  //input里面的值默认是字符串,获取里面的值使用 Math.abs() 方法 或 Number() 转为数字,如果转成功,就是数字。
  //与input里面的值相比(不比较数据类型),两个相同则表示成功转换。
  //也可以判断 Math.abs 的返回,如果是 NaN 就不是数字。
  ipt[1].onclick=function(){
    console.log(Math.abs(ipt[0].value))
    if((Math.abs(ipt[0].value)==ipt[0].value) && ipt[0].value!=""){
      console.log("是数字")
    }else{
      console.log("不是数字")
    }
</script>
</body>
</html>

 还可以把字符串转换成数组,再判断每一位判断每一位的 unicode 是不是在 48 和 57 之间,些方法还就考虑负数、小数。