检查变量是否包含Javascript中的数值? [英] Check if a variable contains a numerical value in Javascript?
问题描述
在PHP中,它非常简单:
In PHP, it's pretty easy:
is_numeric(23);//true
is_numeric("23");//true
is_numeric(23.5);//true
is_numeric(true);//false
但我如何在Javascript中执行此操作?
我可以使用正则表达式,但是它有一个函数吗?
But how do I do this in Javascript? I could use a regular expression, but is there a function for this?
推荐答案
怎么样:
function isNumber(n){
return typeof(n) != "boolean" && !isNaN(n);
}
isNaN 内置函数用于检查值是否不一个数字。
The isNaN built-in function is used to check if a value is not a number.
更新:Christoph是对的,在JavaScript中,布尔类型可转换为Number,返回1表示true,0表示false表示错误,因此如果评估 1 + true
结果将为2.
Update: Christoph is right, in JavaScript Boolean types are convertible to Number, returning the 1 for true and 0 for false, so if you evaluate 1 + true
the result will be 2.
考虑到这种行为,我更新了函数以防止将布尔值转换为其数字表示。
Considering this behavior I've updated the function to prevent converting boolean values to its numeric representation.
这篇关于检查变量是否包含Javascript中的数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!