type checking in javascript

后端 未结 8 863
Happy的楠姐
Happy的楠姐 2020-12-13 11:48

How can I check if a variable is currently an integer type? I\'ve looked for some sort of resource for this and I think the === operator is important, but I\'m not sure how

相关标签:
8条回答
  • 2020-12-13 12:42

    A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

    You can test if the variable contains a number, and if that number is an integer.

    (typeof foo === "number") && Math.floor(foo) === foo
    

    If the variable might be a string containing an integer and you want to see if that is the case:

    foo == parseInt(foo, 10)
    
    0 讨论(0)
  • 2020-12-13 12:45

    Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:

    function isInt(x) {
      return typeOf(x, 'Number') && x % 1 == 0;
    }
    

    The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2

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