代码之家  ›  专栏  ›  技术社区  ›  Richard Knop

检查变量是否为数字

  •  29
  • Richard Knop  · 技术社区  · 15 年前

    如何检查变量是数字,是整数还是字符串数字?

    在PHP中,我可以做到:

    if (is_int($var)) {
        echo '$var is integer';
    }
    

    或:

    if (is_numeric($var)) {
        echo '$var is numeric';
    }
    

    如何在jQuery/JavaScript中实现这一点?

    10 回复  |  直到 15 年前
        1
  •  41
  •   AAA    15 年前

    javascript函数 isNaN(variable)

        2
  •  26
  •   Community kfsone    7 年前

    我会和你一起去

    isFinite(String(foo))
    

    看见 this answer 为了解释原因。如果只希望接受整数值, look here .

        3
  •  10
  •   JonnyRaa    10 年前

    我对javascript非常陌生,但它似乎 typeof(blah) 允许您检查某个内容是否为数字(字符串不表示为true)。A知道OP要求字符串+数字,但我认为这可能值得为其他人记录。

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

    这是 the docs

    下面是一些控制台运行,说明了什么类型的生成:

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

    typeof(NaN);
    "number"
    

    但如果没有类似的东西,它就不会是javascript,对吧?!

        4
  •  2
  •   Mechisso    6 年前

    你应使用:

    if(Number.isInteger(variable))
       alert("It is an integer");
    else
       alert("It is not a integer");
    

    您可以在以下位置找到参考: Number.isInteger()

        5
  •  1
  •   Decent Dabbler    15 年前
    function isNumeric( $probe )
    {
        return parseFloat( String( $probe ) ) == $probe;
    }
    
        6
  •  1
  •   Paresh Mayani jeet    10 年前

    你应使用:

    var x = 23;
    var y = 34hhj;
    
    isNaN(x); 
    isNaN(y); 
    

        7
  •  1
  •   moffeltje    9 年前

    看见 isNan

        8
  •  1
  •   AnomalySmith DevAlien    8 年前

    '' ' ' 将被视为数字 isNaN isFinite .

        9
  •  0
  •   Skull    9 年前

    使用“if条件”检查给定值是否为数字的简单方法

    function isInteger(value)      
    {       
        num=value.trim();         
        return !(value.match(/\s/g)||num==""||isNaN(num)||(typeof(value)=='number');        
    }
    

    如果传递的值是整数,则返回true。。

    solved for     
    value=""      //false null     
    value="12"    //true only integers       
    value="a"     //false     
    value=" 12"   //false      
    value="12 "   //false         
    value=" "     //false space        
    value="$12"   //false special characters 
    value="as12"    //false
    
        10
  •  0
  •   Petter Friberg Onceler    8 年前

    你应使用: $.isNumeric( i )

    jQuery.isNumeric API

        11
  •  0
  •   MD SHAYON    3 年前

    typeof运算符返回一个字符串,指示未赋值操作数的类型。

    const num = 42;
    console.log(typeof num === "number"); // expected return true
    if(typeof num === "number"){
       console.log("This is number")
    }

    更多关于它。。。。。。

    console.log(typeof 42);
    // expected output: "number"
    
    console.log(typeof 'blubber');
    // expected output: "string"
    
    console.log(typeof true);
    // expected output: "boolean"
    
    console.log(typeof undeclaredVariable);
    // expected output: "undefined"