使用JavaScript / jQuery进行简单的数字验证 [英] Simple number validation using JavaScript / jQuery

查看:85
本文介绍了使用JavaScript / jQuery进行简单的数字验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript / jQuery中是否有任何简单方法来检查变量是否为数字(最好没有插件)?我想提醒变量是否为数字。

Is there any simple method in JavaScript / jQuery to check whether the variable is a number or not (preferably without a plugin)? I want to alert whether the variable is a number or not.

提前致谢... :)

Thanks in advance...:)

推荐答案

我不推荐 isNaN 函数来检测数字,因为Java Script类型强制。

I wouldn't recommend the isNaN function to detect numbers, because of the Java Script type coercion.

Ex:

isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!

您还应该记住 isNaN 将为浮点数返回false(是数字)。

You should also bear in mind that isNaN will return false (is number) for floating point numbers.

isNaN('1e1'); // is number
isNaN('1e-1'); // is number

我建议使用功能改为:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

这篇关于使用JavaScript / jQuery进行简单的数字验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆