type checking in javascript

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

    I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.

    function isFloat( x )
    {
        return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
    }
    

    Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.

    Ex.

    alert(isFloat(5.2));   //returns true
    alert(isFloat(5));     //returns false
    alert(isFloat(5.0));   //return could be either true or false
    

提交回复
热议问题