Check that variable is a number

前端 未结 10 1621
陌清茗
陌清茗 2020-12-29 20:38

How can I check that a variable is a number, either an integer or a string digit?

In PHP I could do:

if (is_int($var)) {
    echo \'$var is integer\'         


        
10条回答
  •  无人及你
    2020-12-29 21:34

    I'm pretty new to javascript but it seems like typeof(blah) lets you check if something is a number (it doesn't say true for strings). A know the OP asked for strings + numbers but I thought this might be worth documenting for other people.

    eg:

    function isNumeric(something){
        return typeof(something) === 'number';
    }
    

    Here are the docs

    and here's a few console runs of what typeof produces:

    typeof(12);
    "number"
    typeof(null);
    "object"
    typeof('12');
    "string"
    typeof(12.3225);
    "number"  
    

    one slight weirdness I am aware of is

    typeof(NaN);
    "number"
    

    but it wouldn't be javascript without something like that right?!

提交回复
热议问题