Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 72 期(W3C 标准-ECMAScript-语法):判断整数 #75

Open
wingmeng opened this issue Jul 28, 2019 · 0 comments
Open

第 72 期(W3C 标准-ECMAScript-语法):判断整数 #75

wingmeng opened this issue Jul 28, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jul 28, 2019

如何判断一个数是否为整数?

  • 方式1:任何整数都会被1整除

    value % 1 === 0;
  • 方式2:整数取整后还是等于自己

    Math.floor(value) == value;
  • 方式3:通过位运算判断

    (value | 0)  == value;

其实 JS 原生有个判断整数的方法:isInteger,不过 IE 不支持,所以要兼容的话我们得这样写:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
          isFinite(value) &&
          Math.floor(value) === value;  // 这句用了上面的方法2
};

Number.isInteger(Math.PI);  // false
Number.isInteger(NaN);  // false
@wingmeng wingmeng changed the title 第 72 期(JavaScript-ECMAScript-语法):判断整数 第 72 期(W3C 标准-ECMAScript-语法):判断整数 Jul 28, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant