type checking in javascript

后端 未结 8 883
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: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

提交回复
热议问题