問(wèn)題描述
我決定用一個(gè)非常簡(jiǎn)單的算法創(chuàng)建簡(jiǎn)單的 isEven 和 isOdd 函數(shù):
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 具有某些參數(shù),那沒(méi)關(guān)系,但在許多情況下都失敗了.因此,我著手創(chuàng)建強(qiáng)大的函數(shù),為盡可能多的場(chǎng)景提供正確的結(jié)果,以便只測(cè)試 javascript 數(shù)字范圍內(nèi)的整數(shù),其他所有內(nèi)容都返回 false(包括 + 和 - 無(wú)窮大).請(qǐng)注意,零是偶數(shù).
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));
任何人都可以看到上述任何問(wèn)題嗎?是否有更好(即更準(zhǔn)確、更快或更簡(jiǎn)潔而不會(huì)混淆)的版本?
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
有各種與其他語(yǔ)言相關(guān)的帖子,但我似乎找不到 ECMAScript 的最終版本.
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
推薦答案
使用模數(shù):
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
您可以檢查 Javascript 中的任何值是否可以強(qiáng)制轉(zhuǎn)換為數(shù)字:
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
最好在 isEven
和 isOdd
函數(shù)之外進(jìn)行此檢查,因此您不必在兩個(gè)函數(shù)中重復(fù)錯(cuò)誤處理.
This check should preferably be done outside the isEven
and isOdd
functions, so you don't have to duplicate error handling in both functions.
這篇關(guān)于測(cè)試一個(gè)值是奇數(shù)還是偶數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!