How to determine if a number is odd in JavaScript

后端 未结 27 1648
一向
一向 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:57

    You can use a for statement and a conditional to determine if a number or series of numbers is odd:

    for (var i=1; i<=5; i++) 
    if (i%2 !== 0) {
        console.log(i)
    }
    

    This will print every odd number between 1 and 5.

    0 讨论(0)
  • 2020-11-27 11:02

    One liner in ES6 just because it's clean.

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

    0 讨论(0)
  • 2020-11-27 11:04

    When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).

    function isOdd(value) {
      return typeof value === "number" && // value should be a number
        isFinite(value) &&                // value should be finite
        Math.floor(value) === value &&    // value should be integer
        value % 2 !== 0;                  // value should not be even
    }
    

    If Number.isInteger is available, you may also simplify this code to:

    function isOdd(value) {
      return Number.isInteger(value)      // value should be integer
        value % 2 !== 0;                  // value should not be even
    }
    

    Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.

    Here are some test cases:

    isOdd();         // false
    isOdd("string"); // false
    isOdd(Infinity); // false
    isOdd(NaN);      // false
    isOdd(0);        // false
    isOdd(1.1);      // false
    isOdd("1");      // false
    isOdd(1);        // true
    isOdd(-1);       // true
    
    0 讨论(0)
提交回复
热议问题