How to determine if a number is odd in JavaScript

后端 未结 27 1825
一向
一向 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

    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
    

提交回复
热议问题