Javascript 测试一个值是奇数还是偶数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6211613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing whether a value is odd or even
提问by RobG
I decided to create simple isEvenand isOddfunction with a very simple algorithm:
我决定用一个非常简单的算法创建简单的isEven和isOdd函数:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
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.
如果 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));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
任何人都可以看到上面的任何问题吗?有没有更好(即更准确、更快或更简洁而不会混淆)的版本?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
有各种与其他语言相关的帖子,但我似乎找不到 ECMAScript 的最终版本。
回答by Steve Mayne
Use modulus:
使用模数:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
您可以检查是否可以将 Javascript 中的任何值强制转换为数字:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven
and isOdd
functions, so you don't have to duplicate error handling in both functions.
此检查最好在isEven
和isOdd
函数之外完成,因此您不必在两个函数中重复错误处理。
回答by Robert Brisita
I prefer using a bit test:
我更喜欢使用一点测试:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
这将测试第一位是否表示奇数。
回答by Ivo Renkema
Note: there are also negative numbers.
注意:也有负数。
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
在哪里
function isInteger(n)
{
return n === parseInt(n, 10);
}
回答by nnnnnn
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are notignored and cause both functions to return false.)
以下情况如何?我只在 IE 中对此进行了测试,但是处理表示任何长度的数字的字符串、整数或浮点数的实际数字以及传递布尔值、未定义、空值、数组或对象时这两个函数都返回 false 时非常高兴。(由您决定在传入字符串时是否要忽略前导空格或尾随空格 - 我假设它们不会被忽略并导致两个函数都返回 false。)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
回答by cipher
Why not just do this:
为什么不这样做:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
回答by Raoul Kieffer
To complete Robert Brisita's bit test .
完成 Robert Brisita 的位测试。
if ( ~i & 1 ) {
// Even
}
回答by Fellipe Sanches
We just need one line of code for this!
为此,我们只需要一行代码!
Here a newer and alternative way to do this, using the new ES6syntax for JS functions, and the one-line syntaxfor the if-else
statement call:
这是一种更新的替代方法,使用新的ES6JS 函数语法和if-else
语句调用的单行语法:
const isEven = num => ((num % 2) == 0) ? true : false;
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
回答by Pandemum
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
回答by Eduardo Lucio
A simple modification/improvement of Steve Mayne answer!
史蒂夫梅恩答案的简单修改/改进!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
注意:如果无效则返回false!
回答by Void
A few
一些
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask