How to determine if a number is odd in JavaScript

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

    Every odd number when divided by two leaves remainder as 1 and every even number when divided by zero leaves a zero as remainder. Hence we can use this code

      function checker(number)  {
       return number%2==0?even:odd;
       }
    
    0 讨论(0)
  • 2020-11-27 10:45

    Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)

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

    By using ternary operator, you we can find the odd even numbers:

    var num = 2;
    result = (num % 2 == 0) ? 'even' : 'odd'
    console.log(result);

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

    How about this...

        var num = 3 //instead get your value here
        var aa = ["Even", "Odd"];
    
        alert(aa[num % 2]);
    
    0 讨论(0)
  • 2020-11-27 10:48

    Use my extensions :

    Number.prototype.isEven=function(){
         return this % 2===0;
    };
    
    Number.prototype.isOdd=function(){
         return !this.isEven();
    }
    

    then

    var a=5; 
     a.isEven();
    

    ==False

     a.isOdd();
    

    ==True

    if you are not sure if it is a Number , test it by the following branching :

    if(a.isOdd){
        a.isOdd();
    }
    

    UPDATE :

    if you would not use variable :

    (5).isOdd()
    

    Performance :

    It turns out that Procedural paradigm is better than OOP paradigm . By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .

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

    this works for arrays:

    function evenOrOdd(numbers) {
      const evenNumbers = [];
      const oddNumbers = [];
      numbers.forEach(number => {
        if (number % 2 === 0) {
          evenNumbers.push(number);
        } else {
          oddNumbers.push(number);
        }
      });
    
      console.log("Even: " + evenNumbers + "\nOdd: " + oddNumbers);
    }
    
    evenOrOdd([1, 4, 9, 21, 41, 92]);
    

    this should log out: 4,92 1,9,21,41

    for just a number:

    function evenOrOdd(number) {
      if (number % 2 === 0) {
        return "even";
      }
    
      return "odd";
    }
    
    console.log(evenOrOdd(4));
    

    this should output even to the console

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