检查变量是否包含Javascript中的数值? [英] Check if a variable contains a numerical value in Javascript?

查看:120
本文介绍了检查变量是否包含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屋!

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