type checking in javascript

后端 未结 8 897
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)
    

提交回复
热议问题