---
title: "javascript判断数字 "
author: "zhuozuoying"
date: "2008-06-15T11:41:46Z"
tags: []
categories: ["企业架构"]
slug: "javascript"
draft: false
lastmod: "2008-06-15T11:41:46Z"
id: 203448
url: "https://zzy603.iteye.com/blog/203448"
---

javascript没有直接判断是否是数字的函数。我编程进行翻页时要判断用户输入的是否为数字，
我在网上看到这样一个判断地函数：

//数字的确定
function isDigit(theNum)
{ 
 var theMask = "0123456789";
    if (isEmpty(theNum)) return (false);
 else if (theMask.indexOf(theNum) == -1) return (false);
 return (true);
}
当时没有深究，用上去发现能用。现在发现其原来是不准确的，因为数字在10以内都还好，超过10就不对了。

indexof函数其实是一个找子串的函数，所以很明显上面的程序不对。网上还有使用循环来判断地，具体来说就是根据长度，一次取一个字符判断是不是数字，不过我总感觉这样太烦，效率低。下面这个可能就是简单高效了,挺好用的：
<html>
<title></title>
<head>
</head>
<body>
<form>
<table>
<tr>
      <td class="title">索引</td>
      <td><s:textfield name="dictionary.index" onblur="onlyNum (this.value);"/>
      </td>
    </tr>
</table>
</form>
<script language=javascript>
 
   function onlyNum(number)
   {
	if(number!="")
	{
	         var r,re;
		re = /\d*/i; //\d表示数字,*表示匹配多个数字
		r = number.match(re);
		if(r==number)
		{
		    return true;	
		}else
		{
		    window.alert("索引类型不正确!请输入数据型...");

	            document.forms.index.value="";//清空文本值
		   document.forms.index.focus();//获得光标
                       return false;
		}
		}
	
	}
</script>
</body>
</html>