Skip to content

Instantly share code, notes, and snippets.

@leohxj
Created June 2, 2014 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leohxj/18b086008a104ebce900 to your computer and use it in GitHub Desktop.
Save leohxj/18b086008a104ebce900 to your computer and use it in GitHub Desktop.
在JavaScript中判断整型的N种方法
// 你可以使用余数运算(%),将一个数字按1求余,看看余数是不是0。
function isInteger(x) {
return x % 1 === 0;
}
// 通过Math.round()
function isInteger(x) {
return Math.round(x) === x;
}
// 通过位操作检查
// 这个解决方案(跟其它位运算一样)有一个缺陷:它无法处理超过32位的数字。
function isInteger(x) {
return (x | 0) === x;
}
// 通过parseInt()检查
function isInteger(x) {
return parseInt(x, 10) === x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment