Created
June 2, 2014 09:20
-
-
Save leohxj/18b086008a104ebce900 to your computer and use it in GitHub Desktop.
在JavaScript中判断整型的N种方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 你可以使用余数运算(%),将一个数字按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