Find if variable is divisible by 2

2020-02-02 06:08发布

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条回答
ら.Afraid
2楼-- · 2020-02-02 06:42

You can also:

if (x & 1)
 itsOdd();
else
 itsEven();
查看更多
孤傲高冷的网名
3楼-- · 2020-02-02 06:44

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);
    };
})();​
查看更多
做自己的国王
4楼-- · 2020-02-02 06:44
var x = 2;
x % 2 ? oddFunction() : evenFunction();
查看更多
时光不老,我们不散
5楼-- · 2020-02-02 06:46

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.

查看更多
别忘想泡老子
6楼-- · 2020-02-02 06:47

Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:

x % 2 == 0

Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.

查看更多
相关推荐>>
7楼-- · 2020-02-02 06:47

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

array.each { |x| puts x if x % 2 == 0 }

ruby :D

2 4 6 8 10

查看更多
登录 后发表回答