How to determine if a number is odd in JavaScript

后端 未结 27 1633
一向
一向 2020-11-27 10:05

Can anyone point me to some code to determine if a number in JavaScript is even or odd?

相关标签:
27条回答
  • 2020-11-27 10:53

    With bitwise, codegolfing:

    var isEven=n=>(n&1)?"odd":"even";
    
    0 讨论(0)
  • 2020-11-27 10:53

    Using % will help you to do this...

    You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:

    odd function:

    var isOdd = function(num) {
      return 'number'!==typeof num ? 'NaN' : !!(num % 2);
    };
    

    even function:

    var isEven = function(num) {
      return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
    };
    

    and call it like this:

    isOdd(5); // true
    isOdd(6); // false
    isOdd(12); // false
    isOdd(18); // false
    isEven(18); // true
    isEven('18'); // 'NaN'
    isEven('17'); // 'NaN'
    isOdd(null); // 'NaN'
    isEven('100'); // true
    
    0 讨论(0)
  • 2020-11-27 10:54

    in ES6:

    const isOdd = num => num % 2 == 1;

    0 讨论(0)
  • 2020-11-27 10:54

    A more functional approach in modern javascript:

    const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
    
    const negate = f=> (...args)=> !f(...args)
    const isOdd  = n=> NUMBERS[n % 10].indexOf("e")!=-1
    const isEven = negate(isOdd)
    
    0 讨论(0)
  • 2020-11-27 10:57

    This can be solved with a small snippet of code:

    function isEven(value) {
        return !(value % 2)
    }
    

    Hope this helps :)

    0 讨论(0)
  • 2020-11-27 10:57
    if (X % 2 === 0){
    } else {
    }
    

    Replace X with your number (can come from a variable). The If statement runs when the number is even, the Else when it is odd.

    If you just want to know if any given number is odd:

    if (X % 2 !== 0){
    }
    

    Again, replace X with a number or variable.

    0 讨论(0)
提交回复
热议问题