写一个方法判断一个数字是否为整数

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 like Infinity and NaN.

  • 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.

posted @   王铁柱6  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示