Find if variable is divisible by 2

前端 未结 12 498
梦谈多话
梦谈多话 2020-12-07 19:22

How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.

相关标签:
12条回答
  • 2020-12-07 19:58

    Please write the following code in your console:

    var isEven = function(deep) {
    
      if (deep % 2 === 0) {
            return true;  
        }
        else {
            return false;    
        }
    };
    isEven(44);
    

    Please Note: It will return true, if the entered number is even otherwise false.

    0 讨论(0)
  • 2020-12-07 19:59

    You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.

    var x = 2;
    if (x % 2 == 0)
    {
      alert('even');
    }
    else
    {
      alert('odd')
    }
    
    0 讨论(0)
  • 2020-12-07 20:00

    You can also:

    if (x & 1)
     itsOdd();
    else
     itsEven();
    
    0 讨论(0)
  • 2020-12-07 20:01
    if (x & 1)
     itIsOddNumber();
    else
     itIsEvenNumber();
    
    0 讨论(0)
  • 2020-12-07 20:04

    Seriously, there's no jQuery plugin for odd/even checks?

    Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.

    Source code is also available at http://jsfiddle.net/7HQNG/

    Test-suites are available at http://jsfiddle.net/zeuRV/

    (function() {
        /*
         * isEven(n)
         * @args number n
         * @return boolean returns whether the given number is even
         */
        jQuery.isEven = function(number) {
            return number % 2 == 0;
        };
    
        /* isOdd(n)
         * @args number n
         * @return boolean returns whether the given number is odd
         */
        jQuery.isOdd = function(number) {
            return !jQuery.isEven(number);
        };
    })();​
    
    0 讨论(0)
  • 2020-12-07 20:04
    var x = 2;
    x % 2 ? oddFunction() : evenFunction();
    
    0 讨论(0)
提交回复
热议问题