测试一个值是奇数还是偶数

发布于 2024-11-11 03:52:24 字数 1743 浏览 1 评论 0原文

我决定使用非常简单的算法创建简单的 isEvenisOdd 函数:

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 的明确版本。

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);
}

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?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

吃不饱 2024-11-18 03:52:24

使用模数:

function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}

您可以检查 Javascript 中的任何值是否可以强制转换为数字:

Number.isFinite(parseFloat(n))

此检查最好在 isEvenisOdd 函数之外完成,这样您就不会'不必在两个函数中重复错误处理。

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:

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.

谎言 2024-11-18 03:52:24

我更喜欢使用位测试:

if(i & 1)
{
    // ODD
}
else
{
    // EVEN
}

这测试第一位是否表示奇数。

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.

旧人九事 2024-11-18 03:52:24

下面的怎么样?我只在 IE 中测试了这个,但它很乐意处理表示任何长度的数字、整数或浮点数的实际数字的字符串,并且当传递布尔值、未定义、null、数组或对象时,两个函数都返回 false。 (由您决定是否要在传入字符串时忽略前导空格或尾随空格 - 我假设它们不会被忽略并导致两个函数都返回 false。)

function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}

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 not ignored and cause both functions to return false.)

function isEven(n) {
   return /^-?\d*[02468]$/.test(n);
}

function isOdd(n) {
   return /^-?\d*[13579]$/.test(n);
}
爱要勇敢去追 2024-11-18 03:52:24

注意:也有负数。

function isOddInteger(n)
{
   return isInteger(n) && (n % 2 !== 0);
}

其中

function isInteger(n)
{
   return n === parseInt(n, 10);
}

Note: there are also negative numbers.

function isOddInteger(n)
{
   return isInteger(n) && (n % 2 !== 0);
}

where

function isInteger(n)
{
   return n === parseInt(n, 10);
}
痕至 2024-11-18 03:52:24

完成罗伯特·布里西塔的位测试。

if ( ~i & 1 ) {
    // Even
}

To complete Robert Brisita's bit test .

if ( ~i & 1 ) {
    // Even
}
夜空下最亮的亮点 2024-11-18 03:52:24
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
归属感 2024-11-18 03:52:24

为什么不这样做:

    function oddOrEven(num){
        if(num % 2 == 0)
            return "even";
        return "odd";
    }
    oddOrEven(num);

Why not just do this:

    function oddOrEven(num){
        if(num % 2 == 0)
            return "even";
        return "odd";
    }
    oddOrEven(num);
冰葑 2024-11-18 03:52:24

几个

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

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
千里故人稀 2024-11-18 03:52:24

我们只需要一行代码即可!

这是一种更新的替代方法,使用新的 ES6 语法,以及 单行语法 用于 if -else 语句调用:

const isEven = num => ((num % 2) == 0);

alert(isEven(8));  //true
alert(isEven(9));  //false
alert(isEven(-8)); //true

We just need one line of code for this!

Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:

const isEven = num => ((num % 2) == 0);

alert(isEven(8));  //true
alert(isEven(9));  //false
alert(isEven(-8)); //true
内心旳酸楚 2024-11-18 03:52:24
var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};
var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};
ζ澈沫 2024-11-18 03:52:24

对史蒂夫·梅恩答案的简单修改/改进!

function isEvenOrOdd(n){
    if(n === parseFloat(n)){
        return isNumber(n) && (n % 2 == 0);
    }
    return false;
}

注意:如果无效则返回false!

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!

罪歌 2024-11-18 03:52:24

罗伯特·布里西塔的回答非常棒!但是,我希望该解决方案成为 JS Number 原型的一部分,以便可以在任何数字变量上调用它,而不是将变量传递到函数中。此外,我想要一个能够为浮点数返回 null 的解决方案,因为它们不应被视为偶数或奇数。请参阅下面的我的原型解决方案:

Number.prototype.even = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) === 0
  }
}

Number.prototype.odd = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) !== 0
  }
}

您现在可以对任何数值变量调用这些方法。请参阅下面的一些测试:

let zero = 0
let posOddInt = 1
let posEvenInt = 2
let posFloat = 1.5
let negOddInt = -1
let negEvenInt = -2
let negFloat = -1.5

zero.even() // true
posOddInt.even() // false
posEvenInt.even() // true
posFloat.even() // null
negOddInt.even() // false
negEvenInt.even() // true
negFloat.even() // null

zero.odd() // false
posOddInt.odd() // true
posEvenInt.odd() // false
posFloat.odd() // null
negOddInt.odd() // true
negEvenInt.odd() // false
negFloat.odd() // null

The answer from Robert Brisita is great! However, I wanted the solution to be part of the JS Number prototype so that it could be called on any numeric variable rather than passing the variable into a function. Furthermore, I wanted a solution that would return null for floats as they should be considered neither even nor odd. See below for my prototype solution:

Number.prototype.even = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) === 0
  }
}

Number.prototype.odd = function() {
  if (this % 1 !== 0) {
    return null
  } else {
    return (this & 1) !== 0
  }
}

You can now call these methods on any numeric variable. See below for a few tests:

let zero = 0
let posOddInt = 1
let posEvenInt = 2
let posFloat = 1.5
let negOddInt = -1
let negEvenInt = -2
let negFloat = -1.5

zero.even() // true
posOddInt.even() // false
posEvenInt.even() // true
posFloat.even() // null
negOddInt.even() // false
negEvenInt.even() // true
negFloat.even() // null

zero.odd() // false
posOddInt.odd() // true
posEvenInt.odd() // false
posFloat.odd() // null
negOddInt.odd() // true
negEvenInt.odd() // false
negFloat.odd() // null
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文