How do I check if a JavaScript parameter is a number?

后端 未结 6 1394
一整个雨季
一整个雨季 2021-02-20 13:47

I\'m doing some trouble-shooting and want to add a check that a parameter to a function is a number. How do I do this?

Something like this...

function fn         


        
相关标签:
6条回答
  • 2021-02-20 14:02
    function fn(id){ 
      if((parseFloat(id) == parseInt(id)) && !isNaN(id)){
          return true;
      } else { 
          return false;
      } 
    }
    
    0 讨论(0)
  • 2021-02-20 14:09

    Check if the type is number, and whether it is an int using parseInt:

    if (typeof id == "number" && id == parseInt(id))

    0 讨论(0)
  • 2021-02-20 14:12

    === means strictly equals to and == checks if values are equal. that means "2"==2 is true but "2"===2 is false.

    using regular expression

    var intRegex = /^\d+$/;
    if(intRegex.test(num1)) { 
    //num1 is a valid integer
    }
    

    example of == vs. ===

    0 讨论(0)
  • 2021-02-20 14:18
    function fn(id) {
        return typeof(id) === 'number';
    }
    

    To also check if it’s an integer:

    function fn(id) {
        return typeof(id) === 'number' &&
                isFinite(id) &&
                Math.round(id) === id;
    }
    
    0 讨论(0)
  • 2021-02-20 14:22

    i'd say

     n === parseInt(n)
    

    is enough. note three '===' - it checks both type and value

    0 讨论(0)
  • 2021-02-20 14:22
    function fn(id) {
        var x = /^(\+|-)?\d+$/;
        if (x.test(id)) {
            //integer
            return true;
        }
        else {
            //not an integer
            return false;
        }
    }
    

    Test fiddle: http://jsfiddle.net/xLYW7/

    0 讨论(0)
提交回复
热议问题