javascript - 値が奇数か偶数かをテストする
非常にシンプルなアルゴリズムで、簡単なisEven関数とisOdd関数を作ることにしました。
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
それは 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 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));
上記について何か問題が見える人はいますか?より良い(つまり、より正確で、速く、または難解にならずにより簡潔な)バージョンはありますか?
他の言語に関するさまざまな投稿はありますが、ECMAScriptの決定版は見つけられないようです。
回答 #1
剰余を使う:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
Javascriptの任意の値が次の方法で数値に変換できることを確認できます:
Number.isFinite(parseFloat(n))
このチェックは、できれば isEven 関数と isOdd 関数の外で行うべきです。そうすることで、両方の関数でエラー処理を重複させる必要がなくなります。
回答 #2
ビットテストを使う方が好みです:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
これは、最初のビットがオンかどうかをテストします。オンであれば奇数を意味します。
