我决定用一个非常简单的算法创建简单的isEven和isOdd函数:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
Run Code Online (Sandbox Code Playgroud)
如果n具有某些参数,则可以,但在许多情况下都会失败.所以我开始创建强大的函数,为尽可能多的场景提供正确的结果,这样只测试javascript数量限制内的整数,其他一切都返回false(包括+和 - 无穷大).注意零是偶数.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with …Run Code Online (Sandbox Code Playgroud)