我决定用一个非常简单的算法创建简单的 isEven 和 isOdd 函数:
I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
如果 n 具有某些参数,那没关系,但在许多情况下都失败了.因此,我着手创建强大的函数,为尽可能多的场景提供正确的结果,以便只测试 javascript 数字范围内的整数,其他所有内容都返回 false(包括 + 和 - 无穷大).请注意,零是偶数.
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// 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 empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
任何人都可以看到上述任何问题吗?是否有更好(即更准确、更快或更简洁而不会混淆)的版本?
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
有各种与其他语言相关的帖子,但我似乎找不到 ECMAScript 的最终版本.
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
使用模数:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
您可以检查 Javascript 中的任何值是否可以强制转换为数字:
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
最好在 isEven
和 isOdd
函数之外进行此检查,因此您不必在两个函数中重复错误处理.
This check should preferably be done outside the isEven
and isOdd
functions, so you don't have to duplicate error handling in both functions.
这篇关于测试一个值是奇数还是偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!