写一个方法判断一个数字是否为整数
function isInteger(num) {
// Method 1: Using Number.isInteger() (ES6 and later) - Most straightforward
if (Number.isInteger) {
return Number.isInteger(num);
}
// Method 2: Using modulo operator (%) - Works in older browsers too
return typeof num === 'number' && isFinite(num) && Math.floor(num) === num;
// Method 3: Using parseInt() - Less reliable, avoids type coercion issues
// but can have unexpected behavior with very large numbers.
// return parseInt(num, 10) === num;
}
// Examples
console.log(isInteger(5)); // true
console.log(isInteger(5.0)); // true
console.log(isInteger(5.1)); // false
console.log(isInteger("5")); // false (string, not a number)
console.log(isInteger(NaN)); // false
console.log(isInteger(Infinity)); // false
console.log(isInteger(null)); // false
console.log(isInteger(undefined));// false
Explanation of the methods:
-
Method 1:
Number.isInteger()
: This is the most modern and preferred method. It directly checks if a value is an integer. However, it's not supported in very old browsers (pre-ES6). -
Method 2: Modulo operator (%): This method checks if the remainder of dividing the number by 1 is 0. It also ensures the input is a finite number. This is a good fallback for older browsers.
isFinite(num)
handles cases likeInfinity
andNaN
. -
Method 3:
parseInt()
: This method converts the input to an integer and then compares it to the original value. While it avoids type coercion (automatically converting strings to numbers), it can be unreliable with very large numbers or non-numeric strings. Therefore, it's generally less preferred than the other two methods.
Which method to use?
If you're targeting modern browsers, Number.isInteger()
is the cleanest and most efficient. If you need to support older browsers, the modulo operator method is a robust and reliable alternative. Avoid using parseInt()
unless you have a specific reason and understand its limitations.