写一个方法判断一个数字是否为整数
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通